Skip to the page

Classes and objects · mid

RAII and smart pointers

RAII ties a resource to an object: the constructor gets it and the destructor gives it back, so cleanup happens even on an early return or an exception. Smart pointers use this idea for heap memory.

The notes

What you must know

  • RAII (Resource Acquisition Is Initialization): the constructor acquires a resource (memory, a file, a lock) and the destructor releases it. The destructor runs on every exit from the scope, including a return and an exception.
  • std::string, std::vector, std::ifstream and std::lock_guard all follow RAII, which is why they need no cleanup code.
  • std::unique_ptr owns one object alone and deletes it when the unique_ptr goes out of scope. It cannot be copied, only moved: auto q = std::move(p); leaves p empty.
  • Create one with auto p = std::make_unique<Student>(...); (C++14). Use unique_ptr by default for a heap object with one owner.
  • std::shared_ptr lets several owners share one object. A control block counts the owners, and the object is deleted when the last shared_ptr is destroyed or reset.
  • std::make_shared creates the object and its control block in one allocation.
  • Two objects that hold a shared_ptr to each other form a cycle: the counts never reach zero and the memory leaks. Make one of them a std::weak_ptr, which does not own; call lock() to use it.
  • With RAII types, code needs no raw new or delete, so leaks and double deletes go away.

The red pen

Common traps: mistake → fix

  • Mistake: Smart pointers are garbage collection

    Fix: they delete at a known point: when the owner goes out of scope or the count reaches zero.

  • Mistake: A unique_ptr can be copied

    Fix: it can only be moved.

  • Mistake: shared_ptr never leaks

    Fix: a cycle of shared_ptr leaks; break it with weak_ptr.

  • Mistake: A delete at the end of the function is enough

    Fix: an early return or an exception skips it.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is RAII? Give an example from the standard library.
  2. What is the difference between unique_ptr and shared_ptr?
  3. Why can a unique_ptr not be copied? How do you pass its ownership on?
  4. Two objects point to each other with shared_ptr and are never freed. Why, and how do you fix it?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview