c++ function: pass non const argument to const reference parameter

China☆狼群 提交于 2019-12-18 12:38:08

问题


suppose I have a function which accept const reference argument pass,

int func(const int &i)
{
  /*    */
}

int main()
{
  int j = 1;
  func(j); // pass non const argument to const reference
  j=2; // reassign j
}

this code works fine.according to C++ primer, what this argument passing to this function is like follows,

int j=1;
const int &i = j;

in which i is a synonym(alias) of j,

my question is: if i is a synonym of j, and i is defined as const, is the code:

const int &i = j

redelcare a non const variable to const variable? why this expression is legal in c++?


回答1:


The reference is const, not the object. It doesn't change the fact that the object is mutable, but you have one name for the object (j) through which you can modify it, and another name (i) through which you can't.

In the case of the const reference parameter, this means that main can modify the object (since it uses its name for it, j), whereas func can't modify the object so long as it only uses its name for it, i. func could in principle modify the object by creating yet another reference or pointer to it with a const_cast, but don't.




回答2:


const int &i = j;

This declares a reference to a constant integer. Using this reference, you won't be able to change the value of the integer that it references.

You can still change the value by using the original variable name j, just not using the constant reference i.



来源:https://stackoverflow.com/questions/9127168/c-function-pass-non-const-argument-to-const-reference-parameter

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