Skip to content
UniCircle
MediumConceptualMemory management

RAII and smart pointers: unique_ptr, shared_ptr and weak_ptr

Question CPP-MEM-002

What is RAII? Compare std::unique_ptr, std::shared_ptr and std::weak_ptr, and say when you would use each instead of raw new/delete.

Show the explanation

RAII ("Resource Acquisition Is Initialisation") ties a resource's lifetime to an object's lifetime. The constructor acquires the resource (memory, a file, a lock, a socket) and the destructor releases it. Destructors run automatically when an object goes out of scope, including when an exception is thrown. So cleanup cannot be forgotten. std::vector, std::string, std::fstream and std::lock_guard are all RAII types.

Smart pointers are RAII for heap objects (<memory>):

OwnershipCopyable?OverheadUse for
unique_ptr<T>exactly one ownerno; move onlynone compared with a raw pointerthe default choice: factory results, members, polymorphic objects in containers
shared_ptr<T>shared; a reference count tracks ownersyesa control block and atomic count updatestrue shared ownership, when it is unclear who will be last to use the object
weak_ptr<T>non-owning observer of a shared_ptryessmallbreaking cycles; caches; checking whether an object is still alive with lock()

Cycles: if two objects hold shared_ptrs to each other, neither count reaches zero and both leak. Make one direction a weak_ptr, for example child-to-parent.

Good habits

  • Create objects with std::make_unique<T>(...) and std::make_shared<T>(...). They are exception-safe, and make_shared uses one allocation for the object and its control block.
  • Pass a raw pointer or reference when a function only uses an object. Pass a smart pointer only when the function takes or shares ownership.
  • Do not create two shared_ptrs separately from the same raw pointer. Each would have its own count, and the object would be deleted twice.
  • Modern C++ code rarely needs a bare new or delete.

Original UniCircle question. Last reviewed 22 Oct 2026.