Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

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

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++?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...