Rules of thumb for C++11:
Pass by value, except when
- you do not need ownership of the object and a simple alias will do, in which case you pass by
- you must mutate the object, in which case, use pass by a non-
- you pass objects of derived classes as base classes, in which case you need to pass by reference. (Use the previous rules to determine whether to pass by
constreference or not.)
Passing by pointer is virtually never advised. Optional parameters are best expressed as a
boost::optional for older std libs), and aliasing is done fine by reference.
C++11’s move semantics make passing and returning by value much more attractive even for complex objects.
Rules of thumb for C++03:
Pass arguments by
const reference, except when
- they are to be changed inside the function and such changes should be reflected outside, in which case you pass by non-
- the function should be callable without any argument, in which case you pass by pointer, so that users can pass
nullptrinstead; apply the previous rule to determine whether you should pass by a pointer to a
- they are of built-in types, which can be passed by copy
- they are to be changed inside the function and such changes should not be reflected outside, in which case you can pass by copy (an alternative would be to pass according to the previous rules and make a copy inside of the function)
(here, “pass by value” is called “pass by copy”, because passing by value always creates a copy in C++03)
There’s more to this, but these few beginner’s rules will get you quite far.