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

前端 未结 3 1341
青春惊慌失措
青春惊慌失措 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 01:59

    It is valid code, because a is not const. A const reference means you cannot modify the refered-to object via the reference.

    0 讨论(0)
  • 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".

    0 讨论(0)
  • 2021-01-19 02:08

    As a reference is just another name to a variable and not the object itself, yes in the snippet you show it can be thought as a read-only reference. The code provided with the reference can only access it but it does not guarantee that the object itself won't be changed in another place of your program.

    0 讨论(0)
提交回复
热议问题