Herb Sutter’s guidelines on passing smart pointers as parameters include the following:
- Copying smart pointers incurs two performance hits:
- Cost of increment and decrement on the internally synchronised reference count
- Scalability woes due to cache contention on the shared reference count
- Passing a shared_ptr by value implies taking shared ownership. A copy is needed anyway, so incurring copying cost is fine.
- Don’t use a const smart_ptr& parameter because it exposes the function to the caller’s lifetime management policy. Use a Widget* instead.
Guideline: Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership.
Guideline: Prefer passing objects by value, *, or &, not by smart pointer.