文字数字是否可变?

发布于 2024-12-22 18:42:56 字数 696 浏览 0 评论 0原文

当然,这不会编译:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ヅ她的身影、若隐若现 2024-12-29 18:42:57

对文字 3: 的右值引用

int && w = 3;

实际上绑定到一个临时值,该临时值是计算表达式 3 的结果。它不受某些柏拉图文字的约束 3.

(以下所有标准参考均来自 2011 年 3 月草案,n3242)

3.10/1“左值和右值”

诸如 12、7.3e5 或 true 之类的文字值也是纯右值

然后 8.5.3“引用”给出了如何绑定引用的规则,直至最后一种情况,其中表示:

否则,将使用非引用复制初始化 (8.5) 的规则从初始化表达式创建并初始化类型为“cv1 T1”的临时变量。然后该引用将绑定到临时对象。

并给出了与您问题中的内容非常接近的示例:

double&& rrd = 2; // rrd refers to temporary with value 2.0

The rvalue reference to the literal 3:

int && w = 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"

The value of a literal such as 12, 7.3e5, or true is also a prvalue

Then 8.5.3 "References" gives the rules for how a reference is bound falls through to the last case, which says:

Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy-initialization (8.5). The reference is then bound to the temporary.

and gives as one example something very close to what's in your question:

double&& rrd = 2; // rrd refers to temporary with value 2.0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文