作者seanooxox (0n羊)
看板C_and_CPP
标题[问题] const int *& 给值的问题
时间Fri Sep 30 18:20:59 2016
开发平台(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):
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 220.135.48.199
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1475230865.A.28A.html
1F:→ pttworld: 「指」标要指得到东西,什麽被指到。 09/30 18:24
这边的指标指到 NULL 啊
※ 编辑: seanooxox (220.135.48.199), 09/30/2016 18:33:47
2F:推 shadow0326: int* const & n = b; 09/30 18:48
3F:→ shadow0326: 就是const修饰到什麽的问题 09/30 18:48
4F:→ pttworld: const int *b = 0; 09/30 19:06
5F:→ seanooxox: 0 在这边就是NULL的意思啊,而且就算换成其他东西也会 09/30 20:17
6F:→ seanooxox: 有一样的错误 09/30 20:17
7F:→ pttworld: 可以尝试全篇翻英丢上,语法解法已给。问题本身不明确。 09/30 20:36
8F:→ seanooxox: 先感谢您的回覆,可能是我表达的不清楚。那我换个方式 09/30 20:57
9F:→ seanooxox: 问问题好了,在我程式码中红色字的那一行,如果拿掉con 09/30 20:57
10F:→ seanooxox: st的修饰,就会变得可以compile,我想知道这个跟rvalue 09/30 20:57
11F:→ seanooxox: 有什麽关联 09/30 20:57
12F:→ pttworld: lr以assignment hand side判定。 09/30 21:46
13F:→ pttworld: 只是编译器认为指定失败,不能,不过而已。 09/30 21:48
14F:→ klsdf: 就我的理解是 (const int) * & 你用一个型态指向const int 09/30 22:27
15F:→ klsdf: 的指标去ref一个int *本来就会跟你说型态错误 09/30 22:28
16F:→ klsdf: 你用(const int) (* const) & 可以过是因为你的pointer是 09/30 22:29
17F:→ klsdf: const不可更改 ref的语意有被推导出来 等其他强者解释 QQ 09/30 22:35
18F:→ klsdf: 就是const int *&是lvalue ref 他应该是a等效为b 09/30 22:37
19F:→ klsdf: 但a是const int, 你*b改了值 *a也会跟着改就语意矛盾 09/30 22:38
20F:推 ralts: b 会先 implicit 转型成 const int* 的 rvalue, 而错误在 r 10/01 03:05
21F:→ ralts: value 只能有 const reference. 10/01 03:05
22F:→ g0010726: 一开始的code红色行给你编译过的话 你就可以做: 10/01 08:20
23F:→ g0010726: const int cint; n = &cint; 10/01 08:21
24F:→ g0010726: *b = 100; //改到cint惹 爆炸 10/01 08:22
25F:→ g0010726: 也就是 想在type的某level加上const,得要一路往上每个 10/01 08:27
26F:→ g0010726: level加const。 除了top level 可以不用管 10/01 08:27