开发者

How to get the value of a value passed by reference in C++

开发者 https://www.devze.com 2022-12-10 16:45 出处:网络
I have a function with the following declaration: void cleanValid(int valid[][4], int &size, int index);

I have a function with the following declaration:

void cleanValid(int valid[][4], int &size, int index);

In implementation of this function I ne开发者_Python百科ed to set another counter equal to the integer size passed by reference. I tried doing something like:

int count;
count = size;

If I'm not mistaken, when I change the value of count it will change the value of size as well. I can't have this happen though. How would I go about copying the value of size into count and keeping them independent?


No, you've got it wrong. When you read from the reference into a non-reference variable, you're not setting up any kind of linkage between the two. You will have an independent copy of the value of size at that time, nothing else.

If you wanted to affect the value of size, you would have to use a reference to it:

int& count = size;

/* ... */    
count= 32;  /* This will change size, too. */


If you don't want size to change, why not pass by value/const reference?

void cleanValid(int valid[][4], int size, int index);

or

void cleanValid(int valid[][4], const int &size, int index);

in both options you ensure size is not changed - by letting the compiler take care of it.


int count = size copies the value of size into count. If you change count since you are modifying a copy, size will remain unaffected.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号