in C++: Is const reference means “read-only view of” or it requires immutability of object being referenced?

前端 未结 3 1342
青春惊慌失措
青春惊慌失措 2021-01-19 01:21

The question can be formulated by example as following: is this snippet of code valid?

int a = 1;
const int& ca = a;
++a; //< Q: Is this valid?
cout &         


        
3条回答
  •  太阳男子
    2021-01-19 02:08

    In this particular case, all you are doing is creating a REFERENCE that is const - meaning that ca can't modify the value it refers to (a in this case).

    A common usage is to pass a const reference to a function:

    void foo(const int& cr)
    {
       ... use cr ... 
    }
    

    This indicates that although the value is a reference, the function foo does not alter the value in cr. It is perfectly valid to call this function with a modifiable int variable, or even something that can't be referenced (for example foo(4); - the value 4 is just a constant, so can't really be used as a reference - the compiler will "fix" this by creating a temporary int variable, and pass the reference to that).

    Of course, this is more commonly used with more complex types than int - for example std::string or std::vector. The main reason in this case is to avoid the value being copied, rather than "I want a reference".

提交回复
热议问题