c++ 기초 - lvalue , rvalue

rvalue 탄생배경

1
2
3
4
5
6
7
8
9
10
11
12
std::vector<float> Math::ConvertToPercentage(const std::vector<float>& scores)
{
    std::vector<float> percentages;
    //여기서 복사를 수행
    return percentages;
}
 
int main()
{
    std::vector<float> scores;
    scores = ConvertToPercentage(scores);
}
cs

 percentages vector 컨테이너를 생성한 뒤 scores값을 복사하는 수행할 때,

위의 코드에선 2번의 복사가 일어난다

1. percentages에 넣을 때.

2. 반환할 때 (percentages는 스택영역에 있기때문에 범위밖으로 벗어날 때 삭제됨)

 

하지만 이걸 rValue가 생기며 바꾸어 주었다.

 

이제 lValue와 rValue를 알아야하는데

 

lValue는 우리가 평소에 알던 변수들이고,

 

//절대 성립할수없는 아래와 같은 경우 ( 상수 , lValue+1 , lValue+lValue, &(참조자) )  : rValue이다.

10 = 20;

(number+1)  = 20;

number+anotherNumber =20;

&number = 20;

 

 

이때 move함수가 바로 lvalue를 rvalue로 만들어주는 함수인데.

 

 

1
2
3
4
5
MyString::MyString(MyString&& other) : mString(other.mString),mSize(other.mSize)
{
    other.mString = nullptr;
    other.mSize = 0;
}
cs

위와 같이 MyString&&를 매개변수로 받는 이동생성자를 만들 시

other를 rValue처럼 lValue에 값을 넘겨주고(진짜 그대로) 임시객체처럼 사라지게 만든다.

 

 

 

  Comments,     Trackbacks