9.3 Lvalue references

주홍영·2022년 3월 13일
0

Learncpp.com

목록 보기
94/199

https://www.learncpp.com/cpp-tutorial/lvalue-references/

Lvalue reference types

lvalue reference는 이미 존재하는 lvalue의 alias로 활용된다
lvalue reference type은 다음과 같은 모습을 하고 있다

int      // a normal int type
int&     // an lvalue reference to an int object
double&  // an lvalue reference to a double object

Lvalue reference variables

우리는 이러한 lvalue reference를 variable로 활용할 수 있다

int main()
{
    int x { 5 };    // x is a normal integer variable
    int& ref { x }; // ref is an lvalue reference variable that can now be used as an alias for variable x

    std::cout << x << '\n';  // print the value of x (5)
    std::cout << ref << '\n'; // print the value of x via ref (5)

    return 0;
}

위 코드에서 ref는 x의 alias 이다
만약 x의 alias인 ref의 값을 수정하면 x 또한 값이 수정된다

Initialization of lvalue references

lvalue reference는 반드시 선언과 동시에 initialization이 필수로 동반되어야 한다

int& invalidRef;

위와 같이 선언만해주고 initializatio을 안해주면 error가 발생한다

또한 lvalue reference는 무조건 const type variable은 받을 수 없다

References can’t be reseated (changed to refer to another object)

한번 initialized 되고나면 이는 다른 lvalue를 참조하도록 수정이 불가능하다

profile
청룡동거주민

0개의 댓글