Smart Pointers: Passing Smart Pointers

In this lesson, we will discuss the rules regarding passing smart pointers.

We'll cover the following

Passing smart pointers is an important topic that is seldom addressed. This process ends with the C++ core guidelines since they have six rules for passing std::shared_ptr and std::unique_ptr.

The Six Rules

The following six rules violate the import dry (don’t repeat yourself) principle for software development. At the end, we have only four rules, which makes life as a software developer a lot easier. Here are the rules.

  1. R.32: Take a unique_ptr<widget> parameter to express that a function assumes ownership of a widget
  2. R.33: Take a unique_ptr<widget>& parameter to express that a function reseats the widget
  3. R.34: Take a shared_ptr<widget> parameter to express that a function is part owner
  4. R.35: Take a shared_ptr<widget>& parameter to express that a function might reseat the shared pointer
  5. R.36: Take a const shared_ptr<widget>& parameter to express that it might retain a reference count to the object ???
  6. R.37: Do not pass a pointer or reference obtained from an aliased smart pointer

Get hands-on with 1000+ tech skills courses.