Is there a difference between foo and bar:
class A
{
Object __o;
void foo(Object& o)
{
__o = o;
}
void bar(Object o)
{
__o = o;
}
}
As I understand it, foo performs no copy operation on object o when it is called, and one copy operation for assignment. Bar performs one copy operation on object o when it is called and another one for assignment. So I can more or less say that foo uses 2 times less memory than bar (if o is big enough). Is that correct ?
Is it possible that the compiler optimises the bar function to perform only one copy operation on o ? i.e. makes __o pointing on the local copy of argument o instead of creating a new copy?
It depends. For example, if the compiler decides to inline the function, obviously there will be no copy since there is no function call.
If you want to be sure, pass by const-reference:
This makes no copies. Note your non-const version requires an lvalue, because the reference is mutable.
foo(Object())wouldn’t work, but temporaries (rvalues) can be bound to a const-reference.Double-underscores in identifiers are reserved for the compiler, by the way.