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>):
| Ownership | Copyable? | Overhead | Use for | |
|---|---|---|---|---|
unique_ptr<T> | exactly one owner | no; move only | none compared with a raw pointer | the default choice: factory results, members, polymorphic objects in containers |
shared_ptr<T> | shared; a reference count tracks owners | yes | a control block and atomic count updates | true shared ownership, when it is unclear who will be last to use the object |
weak_ptr<T> | non-owning observer of a shared_ptr | yes | small | breaking 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>(...)andstd::make_shared<T>(...). They are exception-safe, andmake_shareduses 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
newordelete.
Original UniCircle question. Last reviewed 22 Oct 2026.
