關於C++11右值引用的一個誤解
阿新 • • 發佈:2019-01-08
關於右值引用的一個誤解
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.
所以在例子中的那種用法是“畫蛇添足”。