Smart Pointers

Matthew Clark
Nerd For Tech
Published in
2 min readAug 7, 2024

When using pointers one big problem that can end up happening is memory leaks. This happens when the programmer allocates memory on the heap and forgets to deallocate the memory when the program is don using it. To minimize the risk of this happening we can use what is called a smart pointer.

A smart pointer will work mostly the same as a regular pointer except that it will automatically deallocate and free the memory it uses. There are a couple different types of smart pointers so let’s take a look at them.

The first type is the unique_ptr. A unique_ptr is used when you will have one owner of the pointer. This will prevent multiple pointers to the same thing.

The next type is the shared_ptr. A shared_ptr is used to allow multiple owners of a pointer. This allows for multiple owners of one pointer. It will keep track of the amount of shared_ptr instances that point to the same object and only delete the object when the last shared_ptr is deleted.

The last type is the weak_ptr. A weak_ptr is used to access an object that has one or more shared_ptr instances. The weak_ptr does contribute to the reference count of shared_ptr instances. This type is used to observe objects. It can also be used to break circle references.

Smart pointers are a powerful tool to manage dynamic memory and to avoid memory leaks. This will make your code more safe and prevent any unwanted issues that can occur with raw pointers.

For more information check out official Microsoft documentation.

--

--