C++:R-ValueReference
C++11에서 우측갑(Rvalue)는 아래와 같은 정의를 가지고 있다.
- 좌측값은 어떠한 메모리 위치를 가리키는데,
&
연산자를 통해 그 위치를 참조할 수 있다. 우측값은 좌측값이 아닌 값들이다. - 우측값 참조라 정의한 것들도 좌측값 혹은 우측값이 될 수 있다. 이를 판단하는 기준은, 만일 이름이 있다면 좌측값, 없다면 우측값이다.
Move Semantics
Expression
- c++11 rvalue reference
- [추천] 4.2 값의 유형 (glvalue, prvalue, xvalue)
- lvalue: Left value.
- rvalue: Right value.
- xvalue: eXpiring value (more lifetime).
- glvalue: Generalized lvalue (lvalue + xvalue).
- prvalue: Pure rvalue (rvalue, but not xvalue).
Return by rvalue
- [추천] Stackoverflow: Is returning by rvalue reference more efficient?
- Stackoverflow: C++11 rvalues and move semantics confus
This returns a dangling reference, just like with the lvalue reference case. After the function returns, the temporary object will get destructed. You should return Beta_ab by value, like the following
Now, it's properly moving a temporary Beta_ab object into the return value of the function. If the compiler can, it will avoid the move altogether, by using RVO (return value optimization). Now, you can do the following
And it will move construct the temporary into ab, or do RVO to omit doing a move or copy altogether. I recommend you to read BoostCon09 Rvalue References 101 which explains the matter, and how (N)RVO happens to interact with this.
Your case of returning an rvalue reference would be a good idea in other occasions. Imagine you have a getAB() function which you often invoke on a temporary. It's not optimal to make it return a const lvalue reference for rvalue temporaries. You may implement it like this
struct Beta {
Beta_ab ab;
Beta_ab const& getAB() const& { return ab; }
Beta_ab && getAB() && { return move(ab); }
};
Note that move in this case is not optional, because ab is neither a local automatic nor a temporary rvalue. Now, the ref-qualifier && says that the second function is invoked on rvalue temporaries, making the following move, instead of copy
Universal reference
C++ 포럼에서는 forward reference라고 사용하는데 스캇 마이어스(effective C++ 저자)는 forward reference말고 universal reference라고 사용하는데 자신이 만든 명칭이라 한다.
Universal reference는 형식 연혁(Type Deduction;타입 추론)이 발생되는 경우에 적용된다. 함수 템플릿(Function Template)이나 auto와 같은 상황에 해당한다.
Perfect Forwarding
레퍼런스 붕괴 법칙 (Reference Collapsing Rule)
C++11 전에는 레퍼런스 변수를 다시 레퍼런스 변수로 지정하는 것은 에러가 발생하는 사항이었다. 그러나 C++ 11 에서는 다음과 같은 레퍼런스 붕괴 법칙 (Reference Collapsing Rule)을 도입하게 된다.
- T&의 &의 의미 : T& (L-Value 레퍼런스의 L-Value 레퍼런스는 L-Value 레퍼런스)
- T&의 &&의 의미 : T&(L-Value 레퍼런스의 R-Value 레퍼런스는 L-Value 레퍼런스)
- T&&의 &의 의미 : T&(R-Value 레퍼런스의 L-Value 레퍼런스는 L-Value 레퍼런스)
- T&&의 &&의 의미 : T&&(R-Value 레퍼런스의 R-Value 레퍼런스는 R-Value 레퍼런스)
See also
Favorite site
++i
와 i++
의 LValue, RValue 이유에 대한 논제)