Aar*_*aid 17 c++ const rvalue-reference c++11
当然,这不会编译:
int &z = 3; // error: invalid initialization of non-const reference ....
Run Code Online (Sandbox Code Playgroud)
这将编译:
const int &z = 3; // OK
Run Code Online (Sandbox Code Playgroud)
现在,考虑一下:
const int y = 3;
int && yrr = y; // const error (as you would expect)
int && yrr = move(y); // const error (as you would expect)
Run Code Online (Sandbox Code Playgroud)
但这些下一行确实为我编译.我认为不应该.
int && w = 3;
int && yrr = move(3);
void bar(int && x) {x = 10;}
bar(3);
Run Code Online (Sandbox Code Playgroud)
最后两行不会允许文字3被修改吗?3与const int有什么区别?最后,"修改"文字是否有任何危险?
(g ++ - 4.6(GCC)4.6.2 with -std=gnu++0x -Wall -Wextra)
Mic*_*urr 13
rvalue对文字的引用3:
int && w = 3;
Run Code Online (Sandbox Code Playgroud)
实际上绑定到一个临时表,它是评估表达式的结果3.它不受某些柏拉图文字3的束缚.
(以下所有标准参考均来自2011年3月的草案,n3242)
3.10/1"Lvalues and rvalues"
诸如12,7.3e5或true之类的文字的值也是prvalue
然后8.5.3"引用"给出了引用如何约束的规则落到最后一个案例,其中说:
否则,将使用非参考拷贝初始化(8.5)的规则从初始化表达式创建并初始化类型为"cv1 T1"的临时类型"cv1 T1".然后将引用绑定到临时.
举一个例子,非常接近你问题中的内容:
double&& rrd = 2; // rrd refers to temporary with value 2.0
Run Code Online (Sandbox Code Playgroud)