9.5 Pass by lvalue reference

주홍영·2022년 3월 13일
0

Learncpp.com

목록 보기
96/199

https://www.learncpp.com/cpp-tutorial/pass-by-lvalue-reference/

그렇다면 왜 lvalue reference를 통해서 alias를 굳이 만들어서 사용하는 것일까?

Some objects are expensive to copy

어떠한 object는 pass by copy하기에 너무 클 수도 있다
예를 들어 function call 에서 파라미터에 argument를 넘겨주는데
argument의 데이터가 너무너무 많다고 가정하자
그러면 원래대로 복사해서 넘겨주는 것은 너무 비효율적이다

Pass by reference

이러한 expensive copy를 피하는 방법중 하나는 argument를 pass by reference로 넘겨주는 것이다. 그러면 copy 과정이 없기 때문에 굳이 redundant한 작업을 할필요가 없어 더 효율적이다

#include <iostream>
#include <string>

void printValue(std::string& y) // type changed to std::string&
{
    std::cout << y << '\n';
} // y is destroyed here

int main()
{
    std::string x { "Hello, world!" };

    printValue(x); // x is now passed by reference into reference parameter y (inexpensive)

    return 0;
}

function의 파라미터를 보면 std::string& y로 lvalue reference type인 것을 알 수 있다
이렇게 파라미터를 설정하고 argument를 일반 lvalue로 넘겨주면
copy과정 생략하고 main의 x를 직접 참조해 사용한다

Pass by reference allows us to change the value of an argument

사용방법에 따라 함수를 통해서 argument로 전달받은 lvalue를 직접 조작하고 싶을 수도 있다
이럴 때 pass by reference를 이용하면 caller block에서 lvalue를 직접 조작할 수 있다

Pass by reference to non-const can only accept modifiable lvalue arguments

앞서 배웠던 바에 의하면 lvalue reference는 const lvalue 혹은 rvalue를 bind할 수 없다

#include <iostream>
#include <string>

void printValue(int& y) // y only accepts modifiable lvalues
{
    std::cout << y << '\n';
}

int main()
{
    int x { 5 };
    printValue(x); // ok: x is a modifiable lvalue
	
    const int z { 5 };
    printValue(z); // error: z is a non-modifiable lvalue
	
    printValue(5); // error: 5 is an rvalue
	
    return 0;
}

Pass by const reference

만약 const reference로 bind를 하면
const lvalue, rvalue, modifiable lvalue 모두 bind가 가능하다
다만 함수 내부에서 원본을 조작하는 것은 불가능하다

The cost of pass by value vs pass by reference (advanced)

그런데 pass by ref가 좋으면 다 쓰면 되지 않냐?
일단 상대적인 부분이 있다

만약 메모리가 크거나 클래스 타입의 경우 instantiate될 때 setup 되는 부분들이 있는데
이에 대한 비용이 비쌀 수 있다

이렇게 copy에 대한 비용이 확실히 expensive한 경우 pass by ref가 더 효율적이다

그러나 일반적으로 pass by ref가 근원적으로는 pass by value보다 extra step이 존재해
좀 더 expensive한 작업이다
따라서 copy의 대상이 cheap to copy인 경우에는 pass by value가 더 효율적일 수도 있따

참고로 무자르듯이 딱 정해져 있는 경우가 아니다
cheap to copy는 absolute answer가 없으므로 상황을 봐서 pass by value 혹은 ref를 사용하면 된다

profile
청룡동거주민

0개의 댓글