Smart pointers in c++ enable automatic, exception safe, object lifetime management
- unique_ptr
- shared_ptr
- weak_ptr
- auto_ptr
Smart pointer that owns and manages another object through a pointer and disposes that object the the pointer goes out of scope.
Smart pointer that retains shared ownership of an object through a pointer. Several shared pointer objects may own the the same obejct. The object is destroyed and its memory is deallocated when either of the following happens:
- the last remaining shared_ptr owning the object is destroyed
- the last remaing shared_ptr owning the object is assigned to another pointer via operator= or reset()
Smart pointer that holds a non-owning reference to an object, which is managed by shared pointer. It must be converted to a shared pointer in order to access the referenced object. It may be deleted at any time by someone else. If the original shared pointer is destroyed the object's lifetime is extended until the temporary shared_ptr is destroyed as well. Another use of weak pointer is to break reference cycles formed by objects managed by shared pointer. If such cycle is orphaned the shared_ptr reference counts cannot reach zero and memory is leaked. To prevent this one of the pointers in this cycle can be made weak.