Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in passing const &object vs. const object

Tags:

c++

constants

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?

like image 978
Stefano Borini Avatar asked May 01 '26 17:05

Stefano Borini


2 Answers

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.

like image 65
Armen Tsirunyan Avatar answered May 03 '26 06:05

Armen Tsirunyan


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.

like image 41
Mike Seymour Avatar answered May 03 '26 05:05

Mike Seymour