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
const
reference,
- you must mutate the object, in which case, use pass by a non-
const
lvalue reference,
- 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
const
reference or not.)
Passing by pointer is virtually never advised. Optional parameters are best expressed as a std::optional
(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-
const
reference
- the function should be callable without any argument, in which case you pass by pointer, so that users can pass
NULL
/0
/nullptr
instead; apply the previous rule to determine whether you should pass by a pointer to a const
argument
- 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…