With respect to smart pointers and new C++11/14 features, I am wondering what the best-practice return values and function parameter types would be for classes that have the
What would the best return type be for the factory function?
unique_ptr
would be best. It prevents accidental leaks, and the user can release ownership from the pointer, or transfer ownership to a shared_ptr
(which has a constructor for that very purpose), if they want to use a different ownership scheme.
What is the best parameter type for the utility function?
A reference, unless the program flow is so convoluted that the object might be destroyed during the function call, in which case shared_ptr
or weak_ptr
. (In either case, it can refer to a base class, and add const
qualifiers, if you want that.)
What is the best parameter type for the function that keeps a reference to the object?
shared_ptr
or unique_ptr
, if you want it to take responsibility for the object's lifetime and not otherwise worry about it. A raw pointer or reference, if you can (simply and reliably) arrange for the object to outlive everything that uses it.