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
Enginelifetime, whetherControllerorEnginesupports 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,
noexceptmoves, 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
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 Controllerexclusively manage oneEngine?Yes: one controller creates, owns, and tears down a single dedicated engine. Should Controllersupport copying, moving, or inheritance?Move-only and non-polymorphic ( Engineitself may later gain derived implementations).Might an Engineneed to outlive an individualController?No in the default design; the final section addresses multi-controller sharing separately. Who is responsible for freeing the Controllerbuilt bymake_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>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:
- Guaranteed memory leak.
Controller()allocates anEngineon the heap withnew, butControllerhas no destructor (~Controller()). Every destroyedControllerpermanently leakssizeof(Engine)bytes. - Shallow-copy aliasing and double-delete trap. Because
Controllerdeclares no copy operations, the compiler generates a default copy constructor and copy-assignment operator that copy the address stored inengine_, not theEngineitself. 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.- Hidden ownership transfer from the factory.
Controller* make_controller()returns a bare pointer. Nothing in the signature tells the caller "you must calldelete," and any earlyreturnor thrown exception beforedeleteleaks both theControllerand itsEngine. - Ambiguous, const-broken accessor.
Engine* engine() constdoes not tell callers whether they shoulddeletethe returned pointer or how long it remains valid. Worse, it breaks const-correctness (the guarantee that reading through aconstobject cannot mutate its logical state): inside aconstmethod ofController, the memberengine_becomesEngine* const(a read-only pointer to a mutableEngine, notconst Engine*), so a caller holdingconst Controller& ccan still callc.engine()->start()and mutate the engine! - Unnecessary nullability.
new Engine()never returnsnullptr(it throwsstd::bad_allocif out of memory), yet returningEngine*forces every reader and caller to wonder whetherengine()can be null. - Fragile under exceptions. As soon as a second resource is added to
Controller, a throwing constructor leaksengine_(detailed in Step 5).
- Guaranteed memory leak.
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 theunique_ptris 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:
Controllerwrites zero custom destructor, copy, or move functions. When aControllergoes out of scope, the compiler-generated destructor automatically destroysengine_, which deletes theEngine. - Even simpler when
Engineis fixed and concrete: IfEnginenever needs subclasses, mocking, or an incomplete forward-declared type, storeEngine engine_;directly by value insideControllerand returnControllerby value frommake_controller(). That eliminates two heap allocations and makes a nullengine_impossible even after a move. Usestd::unique_ptr<Engine>whenEngineis polymorphic, injected at runtime, hidden behind a compilation firewall (Pimpl), or large and expensive to move. - If
Engineis a polymorphic base class (for exampleElectricEngine : public Engine), giveEngineavirtualdestructor 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 rvalueunique_ptrinto ashared_ptr:std::shared_ptr<Controller> shared = make_controller();.
- Rule of Zero:
Copying, moving, and the moved-from state
Because
std::unique_ptr<Engine>cannot be copied, the compiler automatically marksController's copy constructor and copy-assignment operator as deleted, while still generatingnoexceptmove 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
noexcepton move matters: whenstd::vector<Controller>outgrows its buffer (say from capacity 4 to 8), it only moves existing controllers into the new buffer if moving isnoexcept; 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_isnullptr. Callinga.engine()on the moved-fromawould 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 liveControllerholds anEngine, either storeEngineby 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 callother.engine_->clone()whenEngineis polymorphic.
- The moved-from state: After
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
Controlleracquires 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 thanstd::unique_ptr<Engine>(new Engine(...)): - IfEngine's constructor throws,make_uniquefrees the raw memory automatically. - It keeps nakednewout of complex expressions (prior to C++17,f(std::unique_ptr<Engine>(new Engine()), g())could leak if the compiler rannew Engine(), theng()threw before theunique_ptrconstructor ran).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:
- Tell, don't ask (best when possible): Expose behavior on
Controller(void start_engine() { engine_->start(); }) instead of exposingEngineat all. Callers cannot dangle a reference they never received. - Return references (
Engine&andconst Engine&): When callers genuinely need direct access toEngine, returning a reference signals two facts in the type itself: "this is never null" and "you do not own this—do notdeleteit." Providing both overloads enforces deep constness (const Controlleryieldsconst Engine&). - 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 checkif (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 storesEngineon the stack, inunique_ptr, or inshared_ptr). -void inspect_optional(const Engine* e)— borrows an optional engine that might benullptr. -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 outlivesctrl.- Tell, don't ask (best when possible): Expose behavior on
Shared engines, reference counts, and breaking cycles
What if several controllers must use the same
Engine? Before reaching forstd::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 aVehicleowns oneEngineand twoControllers for the entire trip. KeepEngine(by value orunique_ptr) inVehicle, declared above the controllers so C++ destroys the controllers first and the engine last, and passEngine&into eachController. Zero reference counting, deterministic destruction order! - Case B: True shared lifetime (
std::shared_ptr<Engine>). When controllers are created and destroyed independently and theEnginemust stay alive until the last controller lets go, give each controller astd::shared_ptr<Engine>.std::make_shared<Engine>()allocates theEngineand 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_ptrtoshared_ptrchanges four major properties: 1. Copying is re-enabled:SharedController b = a;now compiles and makesaandbshare the sameEngine(strongincrements 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 toEngine, one to the control block), and copying or destroying ashared_ptrperforms an atomic read-modify-write on the strong count. 3. Thread safety stops at the reference count: Two threads can safely copy and destroyshared_ptr<Engine>copies concurrently, but callingengine_->start()concurrently from two threads still races unlessEngineitself is synchronized (for example, with astd::mutex). 4. Reference cycles leak unless broken withstd::weak_ptr: IfEnginealso storedstd::shared_ptr<SharedController>back-pointers to notify its controllers, both strong counts would stay>= 1forever. Break any back-edge or observer link withstd::weak_ptr(a non-owning smart pointer that watches the control block without incrementing the strong count).- Case A: A parent object owns everything (prefer
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:
Engineleaks on destruction; default shallow copy aliasesengine_(a double-delete time bomb);make_controller()returns an owning raw pointer with no leak protection;Engine* engine() constexposes a mutableEngine*from aconst Controller(engine_becomesEngine* const, notconst Engine*); nullableEngine*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; andstd::weak_ptr<Engine>for expiring observers of shared objects. - Rule of Zero: Using
std::unique_ptr<Engine>insideControllergives automatic cleanup, compile-time prevention of accidental copies, andnoexceptmove 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_ptrfreesEngine), 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) whileEnginemethods are not, copyingControllerbecomes legal again, and back-pointers must usestd::weak_ptrto avoid reference-cycle leaks.
Common mistakes
- Adding
~Controller() { delete engine_; }without touching copy/move operations: Violates the Rule of Three/Five, turningController 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 onunique_ptrrather than value/shared storage) and tempts callers to stashptr.get(). ReturnEngine&/const Engine&instead. - Accepting
std::shared_ptr<Engine>by value in helper functions that only read or callEngine: Forces every caller onto heapshared_ptrallocation and pays an atomic increment + decrement on every call; takeEngine&orconst Engine&instead. - Dereferencing a moved-from
Controller: AfterController b = std::move(a);,a.engine_is null, soa.engine()is undefined behavior unless documented as invalid on moved-from instances. - Creating
std::shared_ptr<Engine>(this)inside anEnginemethod: Allocates a second independent control block for the same address, causing a guaranteed double delete; inherit fromstd::enable_shared_from_this<Engine>and callshared_from_this()instead. - Checking
if (!weak.expired()) weak.lock()->start();across threads: Another thread can drop the lastshared_ptrbetweenexpired()andlock(), makinglock()return null; always lock once withif (auto sp = weak.lock()) { sp->start(); }.
Follow-up questions
- In what situations is a bare
T*orconst T*pointer still the right choice in modern C++ interfaces? A raw pointer (T*orconst T*) is completely idiomatic in modern C++ whenever it is non-owning and optional (meaningnullptrrepresents "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, preferT&/const T&, and never use a raw pointer to own heap memory (deleteshould not appear in application code, matching C++ Core Guideline R.3). - What goes wrong if a team blindly substitutes
std::shared_ptrfor 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 (objectAholdsshared_ptr<B>whileBholdsshared_ptr<A>) keep strong counts at 1 or higher forever, leaking memory silently. Third,shared_ptris twice the size ofunique_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 aunique_ptr, and still leaves the underlyingEngineunsynchronized 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>, storestd::weak_ptr<Engine>—a non-owning smart pointer that points to the shared control block without keeping theEnginealive (use_count()stays unchanged). Before each access, calllock()once to atomically upgrade to a temporaryshared_ptr<Engine>if the target still exists (note that withstd::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 bystd::unique_ptrinstead,weak_ptrdoes 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
Enginea polymorphic base class affect memory layout, copying, and destruction through base pointers? Addingvirtualfunctions 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 eachDerivedobject in memory as[ Base subobject (with vptr) | Derived fields ], destroyed in strict reverse order (~Derivedbody ->Derivedmembers ->~Base). Deleting aDerivedinstance throughBase*(including insidestd::unique_ptr<Base>) when~Base()is notvirtualtriggers undefined behavior—in practice only~Base()executes and everyDerivedmember leaks! Mark polymorphic base destructorsvirtual ~Engine() = default;(orprotectedand non-virtual if callers never delete viaBase*), and delete public copy/move operations onBaseto prevent object slicing (copying only theBasebytes out of aDerivedobject). Whilestd::make_shared<Derived>()happens to store a type-erased deleter in its control block that calls~Derived()even without avirtualdestructor, relying on that is a trap becausestd::unique_ptr<Base>has no control block and still requiresvirtual ~Base().
Follow-up questions
- In what situations is a bare `T*` or `const T*` pointer still the right choice in modern C++ interfaces?
- What goes wrong if a team blindly substitutes `std::shared_ptr` for every raw pointer in a codebase?
- Which pointer type models a nullable, non-owning watcher of an object that might be destroyed first, and how do callers use it safely?
- How does making `Engine` a polymorphic base class affect memory layout, copying, and destruction through base pointers?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes