Skip to content

C++:R-ValueReference

C++11에서 우측갑(Rvalue)는 아래와 같은 정의를 가지고 있다.

  • 좌측값은 어떠한 메모리 위치를 가리키는데, & 연산자를 통해 그 위치를 참조할 수 있다. 우측값은 좌측값이 아닌 값들이다.
  • 우측값 참조라 정의한 것들도 좌측값 혹은 우측값이 될 수 있다. 이를 판단하는 기준은, 만일 이름이 있다면 좌측값, 없다면 우측값이다.

Move Semantics

Expression

Return by rvalue

Beta_ab&&
Beta::toAB() const {
    return move(Beta_ab(1, 1));
}

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

Beta_ab
Beta::toAB() const {
    return Beta_ab(1, 1);
}

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

Beta_ab ab = others.toAB();

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

Beta_ab ab = Beta().getAB();

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

References


  1. Programming_IT_-_Rvalue_reference.pdf 

  2. DevBB-c++0x-RValue_Reference.pdf 

  3. C++98_03-LValue_and_RValue.pdf