Smart Pointers as Objects

Learn the relationship between const and smart pointers as objects.

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 manually.

When we pass a smart pointer by (const) reference, we don’t pass around the shared ownership. In other words, we don’t deal with ownership at all. In this case, there is no need for smart pointers. If you don’t need smart pointers and passing ownership, you should pass around a raw pointer. It will be faster and more readable.

And it will also be faster because you deal directly with the memory address of the pointed value; you don’t have to pass through the layer(s) of a smart pointer.

Types of smart pointers

There are three types of smart pointers in C++. There is no problem with std::weak_ptr in general. It’s not used widely and is therefore considered niche. On the other hand, unique_ptr is often misused. It’s just passed around by const reference because many are unaware of its usage, and to read lengthy C++ error messages.

When a function creates a unique_ptr and returns it, we don’t face any problem.

Get hands-on with 1200+ tech skills courses.