9.11 Return by reference and return by address

주홍영·2022년 3월 13일
0

Learncpp.com

목록 보기
102/199

https://www.learncpp.com/cpp-tutorial/return-by-reference-and-return-by-address/

이전까지 pass by value, ref, address 등을 살펴봤다
cheap to copy는 pass by val이 상관없으나 expensive한 경우에 ref, address가 선호된다

위와 비슷한 문제가 returning value에서도 발생한다
만약 return type이 class인 경우 expesnive할 가능성이 있다

Return by reference

return value를 reference로 하고 싶을 수 있다

#include <iostream>
#include <string>

const std::string& getProgramName() // returns a const reference
{
    static const std::string s_programName { "Calculator" }; // has static duration, destroyed at end of program

    return s_programName;
}

int main()
{
    std::cout << "This program is named " << getProgramName();

    return 0;
}

여기서 함수 내부에서 static 선언으로 변수가 파괴되지 않도록 하면 ref로 전달해도 문제가 생기지 않는다

The object being returned by reference must exist after the function returns

그래서 앞서 코드에서 static으로 변수가 파괴되지 않도록 조치를 취했다
그런데 static으로 선언하기 때문에 만약 const로 설정하지 않으면
function call 이 생길 때마다 값이 의도치 않게 변할 수 있다

Don’t return non-const local static variables by reference

앞서 언급한 문제점 발생의 가능성 때문에
static const ~로 선언하여 방지한다

참고로 const int& 는 일반 int도 pass by ref로 받을 수 있다
하지만 const기 때문에 alias 접근으로는 원본 수정이 불가능하다.

The caller can modify values through the reference

신기한 활용법 중 하나인데 return by ref를 이용해서 값을 조작하는 방법이다

#include <iostream>

// takes two integers by non-const reference, and returns the greater by reference
int& max(int& x, int& y)
{
    return (x > y) ? x : y;
}

int main()
{
    int x{ 5 };
    int y{ 6 };

    max(x, y) = 7; // sets the greater of x or y to 7

    std::cout << x << y;

    return 0;
}

return이 alias 이므로 alias를 lvalue로 놓고 값을 할당하는 작업도 할 수 있는 것이다

Return by address

이 또한 포인터를 return 값으로 사용하는 것인데
ref와 마찬가지로 function의 scope 밖에서도 존재해야지 의미가 있다
만약 그전에 파괴되면 error가 발생할 것이다

그리고 caller 입장에서는 nullptr check를 해줘야 할 것이다

profile
청룡동거주민

0개의 댓글