Reputation: 143775
Suppose you have a function like this one
bool verifyObject(const myObj& obj);
or this one
bool verifyObject(const myObj obj);
As far as I understand, when you pass something like in the second case, a copy is made. However, the compiler might exploit the constness to just pass like in the first case. As such, I see no difference in passing a const object in either way.
Am I wrong?
Upvotes: 3
Views: 751
Reputation: 254431
As far as I understand, when you pass something like in the second case, a copy is made.
Yes; although in some cases (such as when passing a temporary) the copy could be elided.
However, the compiler might exploit the constness to just pass like in the first case.
No; unless the argument is a temporary, this is not one of the situations in which a copy can be elided. When calling the function, the compiler may not even know that the parameter is const
within the function, since a top-level const
like this can be omitted when declaring the function. So even if it can determine that passing a reference would be equivalent to passing a copy (which won't be the case if the copy-constructor or destructor have observable side effects, or if the class has mutable members), it can't change the calling convention since callers would have no way of knowing about that change.
Having said that, if the function is inline, or your compiler does whole-program optimisation, then optimisations such as this are possible; but only if they don't change the program's behaviour.
Upvotes: 2
Reputation: 6039
With the second example (passing by value) the const modifier makes little difference because the compiler will call the copy constructor of the object and pass a copy of it. Passing by const reference (const myObj& obj), on the other hand, only passes a reference to the object (does not make a copy). In that case, the function called cannot change the state of the object through obj.
Upvotes: 1
Reputation: 132984
The second one, from the caller's point of view is equivalent to
bool verifyObject(myObj obj);
Moreover, as declarations, these two are completely equivalent:
bool verifyObject(myObj obj);
bool verifyObject(const myObj obj);
All top-level consts are ignored in function declarations. The difference manifests only during a definition
bool verifyObject(const myObj obj)
{
obj.NonConstMethod(); //compiler error!
}
You cannot modify the copy inside the function, which the caller doesn't care about at all. It's just for your own purposes, as the function implementer.
Upvotes: 3