Smart pointers in C++
-
What are smart pointers
Smart pointers are wrapper classes for pointers. It allows you to automatically destroy heap allocated object and to don't worry about memory leaks in your program.
-
Smart pointers types
There are 3 types of smart pointers:
-
Unique ptr
Unique ptr is scoped pointer. If it gets out of scope it will be deleted with data that is pointing to. It makes sure that only one unique pointer exists. To create unique pointer you usestd::unique_ptr
andstd::make_unique
from#include <memory>
class Entity{ public: Entity(){ std::cout << "created entity" << std::endl; } ~Entity(){ std::cout << "destroyed entity" << std::endl; } }; { std::unique_ptr<Entity> e1 = std::make_unique<Entity>(); } // it will die here
-
Shared ptr
The shared pointer is a reference counting smart pointer that can be used to store and pass a reference beyond the scope. It has reference counter. If all copies gets destroyed it also gets destroyed. To create shared pointer you usestd::shared_ptr
andstd::make_shared
class Entity{ public: Entity(){ std::cout << "created entity" << std::endl; } ~Entity(){ std::cout << "destroyed entity" << std::endl; } }; { std::shared_ptr<Entity> sharedE; { std::shared_ptr<Entity> e0 = std::make_shared<Entity>(); // shared e stores now e0 sharedE = e0; } // sharedE won't die here } // sharedE will die here
-
Weak ptr
A weak pointer is used with a shared pointer, but it does not add to the reference counter like a shared pointer does. To create shared pointer you usestd::weak_ptr
class Entity{ public: Entity(){ std::cout << "created entity" << std::endl; } ~Entity(){ std::cout << "destroyed entity" << std::endl; } }; { std::weak_ptr<Entity> weak; { std::shared_ptr<Entity> e0 = std::make_shared<Entity>(); // weak stores now e0 weak = e0; } // e0 will get destroyed here because weak ptr doesn't add refeerence counter } // weak ptr will point to a free memory
-