Reputation: 7044
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&)
{
}
Upvotes: 2
Views: 1534
Reputation: 12227
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.
Upvotes: 2
Reputation: 44438
In addition to not being able to modify the argument passed in, if TestInfo is a class for example, you'll get compile errors if you try and call non const member functions on it ( Const member functions are functions that promise not to modify the object).
Here are a couple of good reads on const:
Upvotes: 0
Reputation: 206508
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.
Upvotes: 7