Does reference changes the state of the referent

℡╲_俬逩灬. 提交于 2019-12-24 15:44:34

问题


As I read

---references are not pointers it is the object itself,A reference is an entity that is an alias for another object.

---references can never represent NULL

---Reference variables allow two variable names to address the same memory location:

---it cannot later be made to refer to a different object

---A reference is not a variable as a variable is only introduced by the declaration of an object. An object is a region of storage and, in C++, references do not (necessarily) take up any storage.

now does the below line converts the variable integers to a constant integers

const Array& ref = integers

furthermore I read this also which says that you can change the state of a referent.

Please suggest/clarify.


回答1:


No, it does not convert integers. You now just have an alias for integers through which you can't change it. You can still change integers through the original name:

int i = 0;
int const& i_ref = i;
i = 5;
cout << i_ref; // outputs 5

The above examble also shows how you can change the state of the referee.




回答2:


You cannot change the state of a const reference. Apart from that everything you mentioned in there is true.

So for example:

const int& ref = integers;
ref = 5;

will fail to compile. Where as

int& ref = integers;
ref = 5;

will compile and it will change the value stored in integers to 5.

Furthermore a const reference means that you cannot change value of the object it refers using the reference. You can still modify it using the original variable name. For example:

const int& ref = integers;
integers = 5;
std::cout<<ref<<", "<<integers<<std::endl;

is completely valid and will produce:

5, 5     


来源:https://stackoverflow.com/questions/6077332/does-reference-changes-the-state-of-the-referent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!