LR Value의 이해 - ② LR Value와 std::move
L value와 R value는 다음과 같다.
L-Value와 R-Value
int a = 0;
위 코드에서 = 연산자 왼쪽의 값a을 L-Value 라고 하고, 오른쪽 값0을 R-Value라고 한다. 반면 아래의 코드에서는 왼쪽 오른쪽 모두 L-Value 이다.
a = b; // a, b 모두 int 타입 변수
즉, 0 처럼 한번 사용되고 사라지면 R-Value, 재사용 될 수 있으면 L-Value라고 할 수 있다.
아래의 경우 s는 L-Value 이고 "abc"는 R-Value 이다.
std::string s = "abc";
std::move
std::move 함수는 L-Value를 R-Value로 바꿔준다.
int a = 0;
int b = std::move(a);
위 코드에서 b는 L-Value이지만 std::move(a)는 R-Value가 된다.
std::move 정확한 의미는 소유권의 이전에 있다. 아래의 코드는 a의 데이터 abc를 move라는 키워드로 b에게 이전 시키는 예제이다. 따라서 출력 결과 a는 아무 값도 나오지 않고 b에서 abc가 출력됨을 확인할 수 있다.
#include <string>
#include <iostream>
int main()
{
std::string a = "abc";
std::string b = std::move(a);
std::cout << a << std::endl;
std::cout << b << std::endl;
return 0;
}
출력 결과
abc
출처: https://www.youtube.com/channel/UCHcG02L6TSS-StkSbqVy6Fg