9.4 Lvalue references to const

주홍영·2022년 3월 13일
0

Learncpp.com

목록 보기
95/199

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

앞서 말했듯이 일반적인 lvalue reference로는 const variable을 참조할 수 없었다
따라서 const lvalue를 참조하고 싶은 경우 다른 방법을 써야한다

Lvalue reference to const

int main()
{
    const int x { 5 };    // x is a non-modifiable lvalue
    const int& ref { x }; // okay: ref is a an lvalue reference to a const value

    return 0;
}

위와 같이 lvalue reference에 const를 추가해서 사용할 수 있다

Initializing an lvalue reference to const with a modifiable lvalue

그럼 const variable이 아니 일반 modifiable lvalue를 const refer하면 어떻게 될까?

int main()
{
    int x { 5 };          // x is a modifiable lvalue
    const int& ref { x }; // okay: we can bind a const reference to a modifiable lvalue

    std::cout << ref;     // okay: we can access the object through our const reference
    ref = 7;              // error: we can not modify an object through a const reference

    x = 6;                // okay: x is a modifiable lvalue, we can still modify it through the original identifier

    return 0;
}

위의 코드에서처럼 ref에 대입연산자를 이용해 값을 수정할 수가 없다
반면 x는 modifable이므로 수정이 가능하다
alias를 통한 수정이 불가능하다는 것이다

Initializing an lvalue reference to const with an rvalue

const lvalue ref는 rvalue로도 초기화가 가능하다

#include <iostream>

int main()
{
    const int& ref { 5 }; // okay: 5 is an rvalue

    std::cout << ref; // prints 5

    return 0;
}

이는 매우 특수한 사용방법이다

더 나아가

const type& ref에서
ref는 수정자체가 불가능한 것 같다.
즉 다른 variable을 참조하게 바꿀 수가 없는 것 같다
근데 const가 아녀도 ref는 instantiate 되면 바꿀수가 없는 것 같다

profile
청룡동거주민

0개의 댓글