C++ RValue Reference Summary
1. 기존 C++의 레퍼런스
#include <iostream>
class MyClass
{
};
int main(void)
{
MyClass a;
MyClass& b = a; // b가 a를 참조하도록 한다.
}
2. R-Value Reference의 등장
C++11에서 R-Value Reference(&&
)가 추가되어 R-Value 참조가 가능해졌습니다.
#include <iostream>
class MyClass
{
};
int main(void)
{
MyClass a;
MyClass&& c = a; // R-Value Reference 사용
}
3. L-Value와 R-Value의 기본 개념
#include <iostream>
int main(void)
{
int d = 13; // d는 L-Value, 13은 R-Value
int f = 12; // f는 L-Value, 12는 R-Value
d = f;
f = d;
d = d * f;
}
- 대입식의 오른쪽에 등장하는 L-Value는 자동으로 R-Value로 변환됩니다.
a * b
와 같은 연산의 결과는 R-Value이며, 반드시 대입식의 오른쪽에 등장해야 합니다.
4. R-Value의 특성
#include <iostream>
int main(void)
{
int v = d * f;
// d * f = 12; // 에러: R-Value는 대입식의 왼쪽에 올 수 없음
}
- R-Value는 대입식의 오른쪽에만 올 수 있습니다.
- R-Value는 const 성격을 가지며, 한 번 정해지면 변경할 수 없습니다.
- L-Value는 메모리 위치를 가리키며, 값을 할당할 수 있고, &연산자로 주소를 얻을 수 있습니다.
- R-Value는 임시적으로 생성된 값으로, 값을 할당할 수 없고 주소를 얻을 수 없습니다.
5. 함수 반환값과 L-Value/R-Value
#include <iostream>
int main(void)
{
int& foo(); // L-Value 참조를 반환하는 함수
foo() = 12; // 유효: foo()는 L-Value
int* p1 = &foo(); // 유효: L-Value의 주소를 가져옴
}
6. R-Value 반환 함수
#include <iostream>
int main(void)
{
int bar(); // R-Value를 반환하는 함수
int j = 0;
j = bar(); // 유효: R-Value를 대입
// bar() = 5; // 에러: R-Value에 대입할 수 없음
// int* p = &bar(); // 에러: R-Value의 주소를 가져올 수 없음
}
7. L-Value Reference vs R-Value Reference 예제
#include <iostream>
int main(void)
{
// C++98 스타일 L-Value 레퍼런스
int a = 1;
// int& r = 3; // 에러: L-value 참조는 R-Value를 참조할 수 없음
int& ra = a;
std::cout << "Original: L-Value(a): " << a
<< ", L-Value Reference(ra): " << ra << std::endl;
// C++11 R-Value 레퍼런스
int b = 10;
int&& rb = 20; // R-Value 참조는 R-Value를 직접 참조 가능
std::cout << "Original: L-Value(b): " << b
<< ", R-Value Reference(rb): " << rb << std::endl;
rb = b; // R-Value 참조에 L-Value 대입 가능
std::cout << "Modified: L-Value(b): " << b
<< ", R-Value Reference(rb): " << rb << std::endl;
return 0;
}
정리
- R-Value Reference(
&&
)는 C++11에서 도입된 기능입니다. - R-Value Reference는 임시 객체의 수명을 연장하거나, 이동 의미론(Move Semantics)을 구현하는 데 사용됩니다.
- Perfect Forwarding을 구현하는 데에도 중요한 역할을 합니다.
- L-Value Reference(
&
)와 달리 R-Value를 직접 참조할 수 있습니다. - R-Value Reference는 대입식의 오른쪽에 L-Value나 R-Value 모두 올 수 있습니다.
'개발 > C++ (98,03,11,14,17,20,23)' 카테고리의 다른 글
Modern C++ : lvalue, rvalue, value category (2) | 2025.08.17 |
---|---|
Modern C++ : rvalue reference (1) | 2025.08.16 |
Modern C++ : lvalue rvalue reference (98, 11) (2) | 2025.08.15 |
Modern C++ : dynamic heap memory allocation (98, 11, 14) (1) | 2025.08.14 |
Modern C++ : pointer and address (98, 11) (3) | 2025.08.13 |
Modern C++ : const reference and value semantics (98, 11) (1) | 2025.08.12 |
Modern C++ : string vs std::string vs std::array<char, N> (98, 11, 17) (1) | 2025.08.11 |
Modern C++ : array vs std::array (98, 11) (1) | 2025.08.10 |