Smart Pointers
Smart Pointers
There are 4 types of Smart Pointers: Unique Pointer
unique_ptr
, Shared Pointersshared_ptr
, Weak Pointersweak_ptr
, Auto Pointersauto_ptr
.Smart pointers are objects.
Smart pointers are implemented as c++ template classes (like
vector
templates) which can be instantiated.Smart pointers can ONLY point to heap-allocated memory.
Smart pointers call delete when no longer needed.
Smart pointers adhere to RAII (Resource Acquisition Is Initialization) principles. First RAII objects get allocated on the stack. RA (Resource Acquisition) object will acquire some resource, such as opening a file allocating memory that acquires a lock, an so forth. RAII (Initialization), means the resources acquired an object initialization time (which happens in the objects constructor). At some point the need to relinquish that resource that was required and that happens in the destructor.
unique_ptr
Unique Pointers
(unique_ptr)
- simple smart pointer, very efficient!unique_ptr<T>
points to an object of type
T
on the heap.it's unique - there can only be ONE
unique_ptr<T>
pointing to the object on the heapowns what it points to
cannot be assigned or copied
cannot be moved
when the pointer is destroyed, what it points to is automatically destroyed
Shared Pointers
(shared_ptr)
Weak Pointers
(weak_ptr)
Auto Pointers
(auto_ptr)
How To Create A Smart Pointer
#include <memory>
Can't Be Done Using Smart Pointers
Can't do pointer arithmetic on smart pointers like you can with raw pointers.
Last updated