Skip to content

Instantly share code, notes, and snippets.

@aliabidzaidi
Created July 26, 2023 12:43
Show Gist options
  • Save aliabidzaidi/b97459bb6c6fe40613dde4f19149f019 to your computer and use it in GitHub Desktop.
Save aliabidzaidi/b97459bb6c6fe40613dde4f19149f019 to your computer and use it in GitHub Desktop.
C++ dynamic memory

C++ Dynamic memory

Smart pointers in c++ enable automatic, exception safe, object lifetime management

  • unique_ptr
  • shared_ptr
  • weak_ptr
  • auto_ptr

Unique pointer

Smart pointer that owns and manages another object through a pointer and disposes that object the the pointer goes out of scope.

Shared pointer

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()

Weak pointer

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment