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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With