Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

What is RAII, and how do smart pointers implement it?

RAII — Resource Acquisition Is Initialisation — ties a resource's lifetime to an object's lifetime. The constructor acquires it, the destructor releases it. Because C++ guarantees destructors run when an object goes out of scope, including during stack unwinding from an exception, cleanup is automatic and cannot be forgotten.

It applies to any resource, not just memory: file handles, mutex locks, sockets, database connections.

Smart pointers are RAII for heap memory:

  • std::unique_ptr — exclusive ownership. Cannot be copied, only moved. Zero overhead compared to a raw pointer. This should be your default.
  • std::shared_ptr — shared ownership with an atomic reference count; the object is destroyed when the last one goes away. It costs a control block and atomic increments, so use it only when ownership genuinely is shared.
  • std::weak_ptr — observes a shared_ptr without owning it. Its purpose is breaking reference cycles, which shared_ptr alone cannot handle.

Note: Prefer make_unique and make_shared over new. They are exception-safe in argument evaluation, and make_shared allocates the object and control block in one go. The broader point is that in modern C++ you should essentially never write delete.

All C++ interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as