[问题] const int *& 给值的问题

楼主: seanooxox (0n羊)   2016-09-30 18:20:59
开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
G++, Linux
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
问题(Question):
请问各位大大,为什么这段程式码 compile 不过?
小弟跪求解释
int main() {
int *b = 0;
const int *& n = b;
}
错误讯息:
error: invalid initialization of non-const reference of type 'const int*&' from an rvalue of type 'const int*'
我有找到这篇说是因为type-safe 的关系:
http://stackoverflow.com/a/11514730
但是如果把程式改成这样,也没有type-safe,可是却可以成功compile
int a = 0;
int *b = &a;
const int & n = *b;
cout << n << endl; // n = 0
*b = 3;
cout << n << endl; // n = 3
又看到了这篇的回答:http://stackoverflow.com/a/31412466
但是却也看不太懂他的回答是什么意思,为什么它会回传rvalue?
还有,为什么宣告成 const int * const & n = b 就可以compile 过?
感谢各位大大!
程式码(Code):(请善用置底文网页, 记得排版)
http://ideone.com/W5kqRr
补充说明(Supplement):
作者: pttworld (批踢踢世界)   2016-09-30 18:24:00
“指”标要指得到东西,什么被指到。
作者: shadow0326 (非议)   2016-09-30 18:48:00
int* const & n = b;就是const修饰到什么的问题
作者: pttworld (批踢踢世界)   2016-09-30 19:06:00
const int *b = 0;
楼主: seanooxox (0n羊)   2016-09-30 20:17:00
0 在这边就是NULL的意思啊,而且就算换成其他东西也会有一样的错误
作者: pttworld (批踢踢世界)   2016-09-30 20:36:00
可以尝试全篇翻英丢上,语法解法已给。问题本身不明确。
楼主: seanooxox (0n羊)   2016-09-30 20:57:00
先感谢您的回复,可能是我表达的不清楚。那我换个方式问问题好了,在我程式码中红色字的那一行,如果拿掉const的修饰,就会变得可以compile,我想知道这个跟rvalue有什么关联
作者: pttworld (批踢踢世界)   2016-09-30 21:46:00
lr以assignment hand side判定。只是编译器认为指定失败,不能,不过而已。
作者: klsdf (静雨澪)   2016-09-30 22:27:00
就我的理解是 (const int) * & 你用一个型态指向const int的指标去ref一个int *本来就会跟你说型态错误你用(const int) (* const) & 可以过是因为你的pointer是const不可更改 ref的语意有被推导出来 等其他强者解释 QQ就是const int *&是lvalue ref 他应该是a等效为b但a是const int, 你*b改了值 *a也会跟着改就语意矛盾
作者: ralts (拉鲁拉丝)   2016-10-01 03:05:00
b 会先 implicit 转型成 const int* 的 rvalue, 而错误在 rvalue 只能有 const reference.
作者: g0010726 (Kevin)   2016-10-01 08:20:00
一开始的code红色行给你编译过的话 你就可以做:const int cint; n = &cint;*b = 100; //改到cint惹 爆炸也就是 想在type的某level加上const,得要一路往上每个level加const。 除了top level 可以不用管

Links booklink

Contact Us: admin [ a t ] ucptt.com