Smart Pointers

A smart pointer is a type of pointer that is wrapped in a data structure that increases its safety and ergonomics, particularly in memory management of large-scale projects. They are most commonly used in C++, though they do exist in Rust as well. Different types of smart pointers exist with varying specifications. Non-smart pointers are sometimes referred to as raw pointers.

Types of Smart Pointers

Unique Pointers

A unique pointer is a container a raw pointer, which the unique pointer is said to own. A unique pointer explicitly prevents copying of its contained pointer (as would happen with normal assignment), but the std::move function can be used to transfer ownership of the contained pointer to another unique pointer. A unique pointer cannot be copied because its copy constructor and assignment operators are explicitly deleted.

This makes it so that unique pointer is effectively reinforces a pointer that can only have one reference at a time, and whenever that reference goes out of scope, it will automatically call the destructor to the object and free the allocated memory it was pointing to.

This is generally considered as the most common pointer type to use in ‘modern’ C++.

Shared Pointers

Shared pointers are pointers who use reference counting as a mechanism for clean up. As such, many references and copies of shared pointers can exist at a time with no issue, however they incur a performance cost as a result of the refence counting implementation.

It is also argued that shared pointers are a ‘smell’, as they indicate that multiple pieces of code own the same data, which is generally indicative of poor design. This is of course not true in all cases, but beware that they are generally seen as unnecessary in most.

Weak Pointers

Weak pointers are special pointers meant to be used in conjunction with shared pointers. They will point to the share pointer that they are initialized with, but will not participate in reference counting. Weak pointers are most commonly used to break a big issue with shared pointers, which is circular reference. They can also be used to check for dangling pointers. This stack overflow article explains a few common use cases pretty well.