文字数字是否可变?
当然,这不会编译:
int &z = 3; // error: invalid initialization of non-const reference ....
而这将编译:
const int &z = 3; // OK
现在,考虑一下:
const int y = 3;
int && yrr = y; // const error (as you would expect)
int && yrr = move(y); // const error (as you would expect)
但是接下来的几行确实可以为我编译。我认为不应该。
int && w = 3;
int && yrr = move(3);
void bar(int && x) {x = 10;}
bar(3);
最后两行不允许修改文字 3 吗? 3
和 const int 有什么区别?最后,“修改”文字有危险吗?
(g++-4.6 (GCC) 4.6.2 与 -std=gnu++0x -Wall -Wextra
)
Naturally, this won't compile:
int &z = 3; // error: invalid initialization of non-const reference ....
and this will compile:
const int &z = 3; // OK
Now, consider:
const int y = 3;
int && yrr = y; // const error (as you would expect)
int && yrr = move(y); // const error (as you would expect)
But these next lines do compile for me. I think it shouldn't.
int && w = 3;
int && yrr = move(3);
void bar(int && x) {x = 10;}
bar(3);
Wouldn't those last two lines allow the literal 3 to be modified? What is the difference between 3
and a const int? And finally, Is there any danger with 'modifying' literals?
(g++-4.6 (GCC) 4.6.2 with -std=gnu++0x -Wall -Wextra
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对文字
3
: 的右值引用实际上绑定到一个临时值,该临时值是计算表达式
3
的结果。它不受某些柏拉图文字的约束 3.(以下所有标准参考均来自 2011 年 3 月草案,n3242)
3.10/1“左值和右值”
然后 8.5.3“引用”给出了如何绑定引用的规则,直至最后一种情况,其中表示:
并给出了与您问题中的内容非常接近的示例:
The rvalue reference to the literal
3
:is actually bound to a temporary that is the result of evaluating the expression
3
. It's not bound to some Platonic literal 3.(all the following standards references are from the March 2011 draft, n3242)
3.10/1 "Lvalues and rvalues"
Then 8.5.3 "References" gives the rules for how a reference is bound falls through to the last case, which says:
and gives as one example something very close to what's in your question: