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

前端 未结 3 1366
青春惊慌失措
青春惊慌失措 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

    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.

提交回复
热议问题