I read that they are conceptually equal. In practice, is there any occasion that
foo(T t)
is preferred over
foo(const T&
In addition, foo(T t) is normally used when T is a simple type (int, bool, etc).
Built-in types and small objects (such as STL iterators) should normally be passed by value.
This is partly to increase the compiler's opportunities for optimisation. It's surprisingly hard for the compiler to know if a reference parameter is aliasing another parameter or global - it may have to reread the state of the object from memory a number of times through the function, to be sure the value hasn't changed.
This is the reason for C99's restrict
keyword (the same issue but with pointers).
Answered in this answer. This is a SymLink to that answer. Please vote there, if anywhere :)
Two very specific cases:
When you are writing assignment operators with strong exception guarantees you can either write them like
X& X::operator=(const X& orig)
{
X tmp(orig);
swap(this, tmp);
return *this;
}
or you can recognize that the first thing that happens is that you make a copy and just have it done as part of the call
X& X::operator=(X tmp)
{
swap(this, tmp);
return *this;
}
If you have a smart pointer with ownership semantics, e.g. auto_ptr
, and you want to transfer ownership to the called function you should pass it by value. Of course 8 people will now quickly point out that you probably don't want to use auto_ptr
and they're probably right, but sometimes you don't make that choice.
While not at all specific, I frequently end up passing smallish objects around by value when that saves me an allocation on the heap. Not only does the actual allocation and eventual deallocation take time but referencing everything through a pointer does nothing to improve your data locality. It might in other words make a difference to your performance. Exactly where the break-even point is will depend on your application, but I would personally don't hesitate to pass an object that is a few pointer sizes large.
If you want to locally modify t
(without affecting the original) in the body of your method (say in the process of calculating something), the first method would be preferential.