Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing reference in C++ using const var&

Tags:

c++

I have a problem that similar to : this question

But I still don't understand what is the difference between :

void test(TestInfo&)
{

}

and

void test(const TestInfo&)
{

}
like image 324
Rudy Avatar asked Dec 29 '25 20:12

Rudy


2 Answers

The first passes a reference while the second passes an const reference to the function test(),
Note that const reference basically means a reference to a const data.

In the second case you cannot modify the contents of TestInfo inside the function.
Any attempt to modify the passed TestInfo object inside the function would result in a
Undefined Behavior.

like image 164
Alok Save Avatar answered Jan 01 '26 10:01

Alok Save


In addition to what @Als said, the significant of the 2nd is that even though the variable is passed by reference it functions similar to as if passing by value. This can be useful if you are passing a large object. Passing an object by value creates a new object on stack but passing by reference doesn't. When you do const TesetInfo&the new variable will not be created but it will essentially function as if it is passed by value. This will be slightly efficient approach.

like image 33
zar Avatar answered Jan 01 '26 12:01

zar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!