关于右值引用的一个误解
C++11引入了右值引用,但是如果不深入了解而望文生义的使用,会造成一些误解。在处理函数返回的时候会有这种典型错误。
一个错误使用的例子
函数 foo()返回对象X,有的亲可能想返回右值引用。
X foo ()
{
X x;
...
return x;
}
于是代码变成了:
X&& foo ()
{
X x;
...
return x; // ERROR: returns reference to nonexisting object
}
请注意这里的用法,由于X不是一个局部的静态对象,所以这种返回是无效的。
实际上,C++11关于返回是如下定义的:
- If X has an accessible copy or move constructor, the compiler may choose to elide the copy. This
is the so-called (named) return value optimization ((N)RVO), which was specified even before C++11 and is supported by most compilers. - Otherwise, if X has a move constructor, x is moved.
- Otherwise, if X has a copy constructor, x is copied.
- Otherwise, a compile-time error is emitted.
所以在例子中的那种用法是“画蛇添足”。