Herb Sutter GotW91: Smart Pointer parameters

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.

Leave a comment

Filed under C++, Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.