Safe C++ Resource Ownership Using RAII and Smart Pointers

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

During a C++ code review, a teammate proposes the following header and factory sketch for managing a hardware subsystem:

class Engine {
public:
    void start();
};

class Controller {
    Engine* engine_;
public:
    Controller() : engine_(new Engine()) {}
    Engine* engine() const { return engine_; }
};

Controller* make_controller() {
    return new Controller();
}

Walk through every memory-management, lifetime, and const-correctness hazard present in these declarations. Then refactor Engine, Controller, and make_controller() around RAII using the narrowest suitable C++ ownership and borrower types—first under exclusive ownership, and then for a variant where multiple Controller instances must access the same Engine.

Scope & Expectations

  • Clarify the intended lifetime invariants upfront (exclusive vs. shared Engine lifetime, whether Controller or Engine supports copying, moving, or subclassing, and how the factory hands off ownership).
  • Pinpoint all defects in the original sketch, including resource leaks, compiler-generated shallow copies, ambiguous raw-pointer getters, broken logical const-ness, and partial-construction failure paths.
  • Present a clean RAII redesign and explain how copy/move traits, noexcept moves, constructor stack unwinding, and non-owning borrower access behave.
  • Contrast exclusive ownership against multi-controller sharing, covering parent-scoped borrowing, reference-counted lifetimes, thread-safety boundaries, and cycle prevention.

Step-by-step walkthrough

  1. Clarify who owns what before touching types

    In C++, ownership means responsibility for destroying an object and freeing its memory at the end of its lifetime. You cannot pick the right pointer, value, or reference type until the lifetime invariants are explicit, so begin by stating four core design questions and the baseline contract:

    Design question Baseline contract
    Does each Controller exclusively manage one Engine? Yes: one controller creates, owns, and tears down a single dedicated engine.
    Should Controller support copying, moving, or inheritance? Move-only and non-polymorphic (Engine itself may later gain derived implementations).
    Might an Engine need to outlive an individual Controller? No in the default design; the final section addresses multi-controller sharing separately.
    Who is responsible for freeing the Controller built by make_controller()? The caller receives full, exclusive ownership of the returned Controller.

    Modern C++ relies on RAII (Resource Acquisition Is Initialization: tying a heap object, file, or lock to a stack-friendly wrapper object whose destructor automatically releases the resource when the wrapper goes out of scope). Smart pointers are standard-library RAII wrappers around raw pointers that encode ownership directly in the type system so the compiler catches lifetime bugs before the program ever runs:

    Who owns the object?
      ├─ Single owner, fixed concrete type   ──► Value member:       T member_;
      ├─ Single owner, heap / polymorphic    ──► Unique smart ptr:   std::unique_ptr<T>
      ├─ Multiple co-owners, last out cleans ──► Shared smart ptr:   std::shared_ptr<T>
      ├─ Borrower (non-owning, never null)   ──► Reference:          T&  or  const T&
      ├─ Borrower (non-owning, may be null)  ──► Raw pointer:        T*  or  const T*
      └─ Observer of shared obj (may expire) ──► Weak smart ptr:     std::weak_ptr<T>
    
  2. Diagnose every lifetime and ownership bug in the sketch

    Look again at the original code:

    class Controller {
        Engine* engine_;
    public:
        Controller() : engine_(new Engine()) {}
        Engine* engine() const { return engine_; }
    };
    
    Controller* make_controller() { return new Controller(); }
    

    Even in 15 lines, there are six distinct defects:

    1. Guaranteed memory leak. Controller() allocates an Engine on the heap with new, but Controller has no destructor (~Controller()). Every destroyed Controller permanently leaks sizeof(Engine) bytes.
    2. Shallow-copy aliasing and double-delete trap. Because Controller declares no copy operations, the compiler generates a default copy constructor and copy-assignment operator that copy the address stored in engine_, not the Engine itself. If someone naively adds ~Controller() { delete engine_; } without disabling or deep-copying copies (violating the Rule of Three, which says that if a class needs a custom destructor, copy constructor, or copy assignment, it almost certainly needs all three), copying crashes or corrupts the heap:
    Controller a;          a.engine_ ──────┐
    Controller b = a;      b.engine_ ──────┼──► [ Engine @ 0x5000 ]
                                           │
    } // end of scope:                     ▼
      1. ~b() runs -> delete 0x5000 (freed)
      2. ~a() runs -> delete 0x5000 AGAIN! (undefined behavior: double free)
    
    Copy assignment (`b = a;`) is even worse: it overwrites `b.engine_`, leaking `b`'s original `Engine`, and then double-deletes `a`'s `Engine` at scope exit.
    
    1. Hidden ownership transfer from the factory. Controller* make_controller() returns a bare pointer. Nothing in the signature tells the caller "you must call delete," and any early return or thrown exception before delete leaks both the Controller and its Engine.
    2. Ambiguous, const-broken accessor. Engine* engine() const does not tell callers whether they should delete the returned pointer or how long it remains valid. Worse, it breaks const-correctness (the guarantee that reading through a const object cannot mutate its logical state): inside a const method of Controller, the member engine_ becomes Engine* const (a read-only pointer to a mutable Engine, not const Engine*), so a caller holding const Controller& c can still call c.engine()->start() and mutate the engine!
    3. Unnecessary nullability. new Engine() never returns nullptr (it throws std::bad_alloc if out of memory), yet returning Engine* forces every reader and caller to wonder whether engine() can be null.
    4. Fragile under exceptions. As soon as a second resource is added to Controller, a throwing constructor leaks engine_ (detailed in Step 5).
  3. Redesign for sole ownership with std::unique_ptr (or by value)

    Replace owning raw pointers with std::unique_ptr<T> (a move-only smart pointer that owns a heap object exclusively and deletes it when the unique_ptr is destroyed, using the same 8 bytes on 64-bit machines as a raw pointer and zero reference-counting overhead):

    #include <memory>
    #include <stdexcept>
    #include <utility>
    
    class Engine {
    public:
        void start();
    };
    
    class Controller {
    public:
        Controller() : engine_(std::make_unique<Engine>()) {}
    
        // Allow callers or unit tests to inject a pre-built (or subclassed) Engine.
        explicit Controller(std::unique_ptr<Engine> engine) : engine_(std::move(engine)) {
            if (!engine_) {
                throw std::invalid_argument("Controller requires a non-null Engine");
            }
        }
    
        // Separate mutable and const accessors preserve deep const-correctness.
        Engine& engine() { return *engine_; }
        const Engine& engine() const { return *engine_; }
    
    private:
        std::unique_ptr<Engine> engine_;
    };
    
    std::unique_ptr<Controller> make_controller() {
        return std::make_unique<Controller>();
    }
    

    Why every piece of this interface pulls its weight:

    • Rule of Zero: Controller writes zero custom destructor, copy, or move functions. When a Controller goes out of scope, the compiler-generated destructor automatically destroys engine_, which deletes the Engine.
    • Even simpler when Engine is fixed and concrete: If Engine never needs subclasses, mocking, or an incomplete forward-declared type, store Engine engine_; directly by value inside Controller and return Controller by value from make_controller(). That eliminates two heap allocations and makes a null engine_ impossible even after a move. Use std::unique_ptr<Engine> when Engine is polymorphic, injected at runtime, hidden behind a compilation firewall (Pimpl), or large and expensive to move.
    • If Engine is a polymorphic base class (for example ElectricEngine : public Engine), give Engine a virtual destructor and explicitly delete public copy/move operations so callers cannot accidentally copy only the base half of a subclass (object slicing):
    class Engine {
    public:
        virtual ~Engine() = default;
        Engine(const Engine&) = delete;
        Engine& operator=(const Engine&) = delete;
        Engine(Engine&&) = delete;
        Engine& operator=(Engine&&) = delete;
    
        virtual void start() = 0;
    
    protected:
        Engine() = default;
    };
    
    • Flexible factory return: Returning std::unique_ptr<Controller> forces clean ownership while staying maximally flexible—if a caller later needs shared ownership, C++ implicitly converts an rvalue unique_ptr into a shared_ptr: std::shared_ptr<Controller> shared = make_controller();.
  4. Copying, moving, and the moved-from state

    Because std::unique_ptr<Engine> cannot be copied, the compiler automatically marks Controller's copy constructor and copy-assignment operator as deleted, while still generating noexcept move constructor and move assignment! That turns the silent double-delete bug into an immediate compile-time error:

    Controller a;                     a.engine_ ──► [ Engine @ 0x5000 ]
    Controller b = a;                 // COMPILE ERROR: copy constructor is deleted!
    
    Controller c = std::move(a);      a.engine_ ──► nullptr
                                      c.engine_ ──► [ Engine @ 0x5000 ]
    

    You can verify these exact traits at compile time with static_assert:

    static_assert(!std::is_copy_constructible_v<Controller>);
    static_assert(!std::is_copy_assignable_v<Controller>);
    static_assert(std::is_nothrow_move_constructible_v<Controller>);
    static_assert(std::is_nothrow_move_assignable_v<Controller>);
    

    Why noexcept on move matters: when std::vector<Controller> outgrows its buffer (say from capacity 4 to 8), it only moves existing controllers into the new buffer if moving is noexcept; otherwise it tries to copy (or loses its strong exception guarantee).

    Two design choices to watch out for:

    • The moved-from state: After Controller c = std::move(a);, a.engine_ is nullptr. Calling a.engine() on the moved-from a would dereference null. That matches standard C++ library types ("valid but unspecified state: safe only to destroy or assign a new value to"). If you want a stronger invariant where every live Controller holds an Engine, either store Engine by value or delete the move operations too.
    • If deep copying is required: Write explicit copy operations that allocate a fresh copy (engine_(std::make_unique<Engine>(*other.engine_))), or call other.engine_->clone() when Engine is polymorphic.
  5. Exception safety during construction

    When an exception is thrown in C++, stack unwinding destroys every local object and every already-constructed member subobject in reverse order of construction. Crucially, if a class's constructor throws partway through, that class's own destructor ~Controller() never runs (because the object never finished being born).

    Compare what happens when Controller acquires two resources and the second one throws:

    Unsafe raw pointers:                           Safe RAII smart pointers:
      Controller()                                   Controller()
        1. engine_ = new Engine()  [0x5000]            1. engine_ = make_unique<Engine>() [0x5000]
        2. sensor_ = new Sensor()  --> THROWS!         2. sensor_ = make_unique<Sensor>() --> THROWS!
        3. ~Controller() DOES NOT RUN!                 3. ~Controller() does not run, BUT
        4. raw pointer engine_ does nothing               member ~unique_ptr<Engine>() DOES run!
        Result: 0x5000 LEAKS forever.                  Result: 0x5000 is deleted cleanly.
    

    Always construct smart pointers with std::make_unique<Engine>(...) rather than std::unique_ptr<Engine>(new Engine(...)): - If Engine's constructor throws, make_unique frees the raw memory automatically. - It keeps naked new out of complex expressions (prior to C++17, f(std::unique_ptr<Engine>(new Engine()), g()) could leak if the compiler ran new Engine(), then g() threw before the unique_ptr constructor ran).

  6. Grant non-owning access without leaking ownership

    Code that merely uses the engine for a moment should never receive or depend on a smart pointer. Order your choices from most encapsulated to most permissive:

    1. Tell, don't ask (best when possible): Expose behavior on Controller (void start_engine() { engine_->start(); }) instead of exposing Engine at all. Callers cannot dangle a reference they never received.
    2. Return references (Engine& and const Engine&): When callers genuinely need direct access to Engine, returning a reference signals two facts in the type itself: "this is never null" and "you do not own this—do not delete it." Providing both overloads enforces deep constness (const Controller yields const Engine&).
    3. Return a raw pointer (Engine* / const Engine*) only when null is valid: For example, if a controller can legitimately have no attached engine, Engine* try_engine() tells callers to check if (auto* e = ctrl.try_engine()).

    Apply the exact same rule to function parameters: - void inspect(const Engine& e) — borrows a required engine (works regardless of whether the caller stores Engine on the stack, in unique_ptr, or in shared_ptr). - void inspect_optional(const Engine* e) — borrows an optional engine that might be nullptr. - void adopt(std::unique_ptr<Engine> e) — takes sole ownership away from the caller. - void share(std::shared_ptr<Engine> e) — becomes a new co-owner alongside the caller.

    Remember that references and raw pointers still require one lifetime rule: borrowers must not stash &ctrl.engine() where it outlives ctrl.

  7. Shared engines, reference counts, and breaking cycles

    What if several controllers must use the same Engine? Before reaching for std::shared_ptr, ask one question: does a single outer object outlive all of those controllers?

    • Case A: A parent object owns everything (prefer unique_ptr + references). Suppose a Vehicle owns one Engine and two Controllers for the entire trip. Keep Engine (by value or unique_ptr) in Vehicle, declared above the controllers so C++ destroys the controllers first and the engine last, and pass Engine& into each Controller. Zero reference counting, deterministic destruction order!
    • Case B: True shared lifetime (std::shared_ptr<Engine>). When controllers are created and destroyed independently and the Engine must stay alive until the last controller lets go, give each controller a std::shared_ptr<Engine>. std::make_shared<Engine>() allocates the Engine and its control block (a small bookkeeping struct holding the atomic strong and weak reference counts) in a single heap allocation:
    auto eng = std::make_shared<Engine>();   // strong = 1
    Controller c1(eng);                      // strong = 2
    Controller c2(eng);                      // strong = 3
    eng.reset();                             // strong = 2  (c1 and c2 still co-own Engine)
    // c1 leaves scope                       // strong = 1
    // c2 leaves scope                       // strong = 0  --> ~Engine() runs automatically!
    
    class SharedController {
    public:
        explicit SharedController(std::shared_ptr<Engine> engine) : engine_(std::move(engine)) {
            if (!engine_) {
                throw std::invalid_argument("SharedController requires a non-null Engine");
            }
        }
    
        Engine& engine() { return *engine_; }
        const Engine& engine() const { return *engine_; }
    
    private:
        std::shared_ptr<Engine> engine_;
    };
    

    Switching from unique_ptr to shared_ptr changes four major properties: 1. Copying is re-enabled: SharedController b = a; now compiles and makes a and b share the same Engine (strong increments by 1). Delete copy operations if shallow sharing of controllers is unintended. 2. Runtime overhead: sizeof(shared_ptr<Engine>) is two pointers (16 bytes on 64-bit: one to Engine, one to the control block), and copying or destroying a shared_ptr performs an atomic read-modify-write on the strong count. 3. Thread safety stops at the reference count: Two threads can safely copy and destroy shared_ptr<Engine> copies concurrently, but calling engine_->start() concurrently from two threads still races unless Engine itself is synchronized (for example, with a std::mutex). 4. Reference cycles leak unless broken with std::weak_ptr: If Engine also stored std::shared_ptr<SharedController> back-pointers to notify its controllers, both strong counts would stay >= 1 forever. Break any back-edge or observer link with std::weak_ptr (a non-owning smart pointer that watches the control block without incrementing the strong count).

Intuition & how it works

Think of heap memory like a house, and pointers like keys vs. the legal property deed. In the original C++ sketch, raw pointers (Engine*, Controller*) hand out unmarked metal keys: nobody can tell by looking at a key whether they are supposed to demolish the house when they leave, or whether someone else has already demolished it while they are still inside. RAII (Resource Acquisition Is Initialization, a C++ pattern where an object's destructor automatically cleans up resources when the object leaves scope) replaces unmarked keys with explicit legal roles: std::unique_ptr<T> is a single physical property deed (only one owner can hold it at a time, and shredding the deed demolishes the house), std::shared_ptr<T> is a co-ownership registry where the last co-owner out turns off the lights, and T& is inviting a guest inside while you keep the deed in your pocket.

Both common beginner "quick fixes" fail in subtle ways. Simply adding ~Controller() { delete engine_; } leaves the compiler's default shallow copy enabled, so Controller b = a; makes two deeds for one house and crashes with a double delete at the end of the scope. Conversely, replacing every raw pointer with std::shared_ptr hides who actually owns the lifetime, adds atomic reference-counting overhead, allows memory leaks through circular references, and lets objects die at unpredictable moments on arbitrary threads.

Trace our redesigned Controller (holding std::unique_ptr<Engine> engine_) through four lines: 1. auto ctrl = make_controller(); allocates Controller and its Engine (say at 0x5000); ctrl is the sole owner (sizeof is 8 bytes on 64-bit, zero reference count). 2. ctrl->engine().start(); borrows the engine via Engine&—non-null, non-owning, and impossible to delete accidentally (const Controller returns const Engine&, preventing mutation). 3. Controller copy = *ctrl; fails to compile immediately because unique_ptr disables copying, while auto moved = std::move(ctrl); transfers 0x5000 to moved and sets ctrl to nullptr in O(1) without throwing. 4. When moved leaves scope (either normally or while an exception unwinds the stack), ~unique_ptr automatically deletes both Controller and Engine with zero manual delete statements.

Key points

  • Six defects in the original sketch: Engine leaks on destruction; default shallow copy aliases engine_ (a double-delete time bomb); make_controller() returns an owning raw pointer with no leak protection; Engine* engine() const exposes a mutable Engine* from a const Controller (engine_ becomes Engine* const, not const Engine*); nullable Engine* hides the non-null invariant; and adding a second raw-pointer member leaks the first if the constructor throws.
  • Pick the most restrictive type that fits: Value member Engine engine_; when concrete and fixed; std::unique_ptr<Engine> for single-owner heap or polymorphic objects; std::shared_ptr<Engine> only when no single outer owner outlives all co-owners; Engine& / const Engine& for non-null borrowers; Engine* for nullable borrowers; and std::weak_ptr<Engine> for expiring observers of shared objects.
  • Rule of Zero: Using std::unique_ptr<Engine> inside Controller gives automatic cleanup, compile-time prevention of accidental copies, and noexcept move operations without writing a single destructor, copy, or move function.
  • Automatic exception safety: During stack unwinding from a failed constructor, C++ destroys already-constructed member subobjects (~unique_ptr frees Engine), whereas raw pointer members do nothing and ~Controller() never runs for a half-built object.
  • Shared lifetimes need extra care: When switching to std::shared_ptr<Engine>, remember that reference-count updates are thread-safe (atomic) while Engine methods are not, copying Controller becomes legal again, and back-pointers must use std::weak_ptr to avoid reference-cycle leaks.

Common mistakes

  • Adding ~Controller() { delete engine_; } without touching copy/move operations: Violates the Rule of Three/Five, turning Controller b = a; into an immediate double-delete bug.
  • Defaulting every pointer to std::shared_ptr: Obscures ownership architecture, enables reference-cycle memory leaks, pays 16-byte pointer + atomic ref-count costs unnecessarily, and makes destruction timing non-deterministic.
  • Returning const std::unique_ptr<Engine>& from a getter: Leaks implementation details (forcing callers to depend on unique_ptr rather than value/shared storage) and tempts callers to stash ptr.get(). Return Engine& / const Engine& instead.
  • Accepting std::shared_ptr<Engine> by value in helper functions that only read or call Engine: Forces every caller onto heap shared_ptr allocation and pays an atomic increment + decrement on every call; take Engine& or const Engine& instead.
  • Dereferencing a moved-from Controller: After Controller b = std::move(a);, a.engine_ is null, so a.engine() is undefined behavior unless documented as invalid on moved-from instances.
  • Creating std::shared_ptr<Engine>(this) inside an Engine method: Allocates a second independent control block for the same address, causing a guaranteed double delete; inherit from std::enable_shared_from_this<Engine> and call shared_from_this() instead.
  • Checking if (!weak.expired()) weak.lock()->start(); across threads: Another thread can drop the last shared_ptr between expired() and lock(), making lock() return null; always lock once with if (auto sp = weak.lock()) { sp->start(); }.

Follow-up questions

  • In what situations is a bare T* or const T* pointer still the right choice in modern C++ interfaces? A raw pointer (T* or const T*) is completely idiomatic in modern C++ whenever it is non-owning and optional (meaning nullptr represents "no object"). Concrete examples include an optional function argument (void attach_logger(Logger* maybe_logger)), a nullable lookup result (Engine* try_engine()), an upward pointer to a parent guaranteed by enclosing scope to outlive the child, or C ABI boundaries. Whenever the borrowed object cannot be null, prefer T& / const T&, and never use a raw pointer to own heap memory (delete should not appear in application code, matching C++ Core Guideline R.3).
  • What goes wrong if a team blindly substitutes std::shared_ptr for every raw pointer in a codebase? First, it erases architectural intent: when everything co-owns everything, object lifetimes become unpredictable, so a heavy destructor (closing sockets or freeing GPU buffers) might run unexpectedly on a real-time control thread that happened to drop the last reference. Second, reference cycles (object A holds shared_ptr<B> while B holds shared_ptr<A>) keep strong counts at 1 or higher forever, leaking memory silently. Third, shared_ptr is twice the size of unique_ptr (16 bytes vs. 8 bytes on 64-bit), allocates a control block, pays atomic CPU instructions on every copy/destroy, cannot be converted back into a unique_ptr, and still leaves the underlying Engine unsynchronized across threads.
  • Which pointer type models a nullable, non-owning watcher of an object that might be destroyed first, and how do callers use it safely? When the target is managed by std::shared_ptr<Engine>, store std::weak_ptr<Engine>—a non-owning smart pointer that points to the shared control block without keeping the Engine alive (use_count() stays unchanged). Before each access, call lock() once to atomically upgrade to a temporary shared_ptr<Engine> if the target still exists (note that with std::make_shared, the combined object + control-block memory allocation is freed only once both strong and weak counts reach zero). If the target is owned by std::unique_ptr instead, weak_ptr does not exist; either have ~Engine() explicitly unregister itself from observers on destruction, or give observers an integer handle/generation ID resolved through an owning registry.

cpp std::weak_ptr<Engine> observer = shared_engine; // does not increment use_count() if (std::shared_ptr<Engine> pinned = observer.lock()) { pinned->start(); // guaranteed alive until `pinned` leaves scope }

  • How does making Engine a polymorphic base class affect memory layout, copying, and destruction through base pointers? Adding virtual functions gives each object a hidden vptr (virtual table pointer, typically 8 bytes on 64-bit systems, pointing to the class's table of function addresses) and lays out each Derived object in memory as [ Base subobject (with vptr) | Derived fields ], destroyed in strict reverse order (~Derived body -> Derived members -> ~Base). Deleting a Derived instance through Base* (including inside std::unique_ptr<Base>) when ~Base() is not virtual triggers undefined behavior—in practice only ~Base() executes and every Derived member leaks! Mark polymorphic base destructors virtual ~Engine() = default; (or protected and non-virtual if callers never delete via Base*), and delete public copy/move operations on Base to prevent object slicing (copying only the Base bytes out of a Derived object). While std::make_shared<Derived>() happens to store a type-erased deleter in its control block that calls ~Derived() even without a virtual destructor, relying on that is a trap because std::unique_ptr<Base> has no control block and still requires virtual ~Base().

Follow-up questions

Similar questions

More Wayve interview questions

All 1 Wayve questions →