Search⌘ K

Smart Pointers as Objects

Understand the role of const in smart pointer usage in C++. Explore how passing unique_ptr and shared_ptr differs, why passing by const reference is often incorrect, and how to manage ownership safely. Learn best practices for using raw pointers versus smart pointers with const to write clearer and safer code.

What is a smart pointer?

An instance of a smart pointer is an object consisting of a raw pointer and some data for lifetime management. The exact internal representation is not important in our case.

In other words, having a smart pointer means that we have a wrapper object around a pointer, and the general principle for class type parameters kicks in. What’s that general principle?

We should pass around class type parameters by reference, preferably by const reference.

We found that passing smart pointers by reference is the result of syntactic difficulties and a lack of understanding in most cases.

The purpose of a smart pointer is proper lifetime management without the need for calling delete ...