Raw Pointers vs Smart Pointers: Ownership, Safety, and Cost
System DesignModel answerLast updated
Explain how C++ smart pointers encode ownership semantics, prevent memory bugs, and compare in runtime cost against raw pointers.
Pointer Semantics in a Performance-Critical C++ Codebase
You are reviewing a legacy C++ codebase that mixes raw pointers with the modern smart pointer types introduced in C++11. Your goal is to establish clear guidelines for when to use each form.
Address the following three areas:
1. Ownership models
Compare how std::unique_ptr and std::shared_ptr represent different ownership policies. When is a raw pointer the right tool rather than either smart pointer?
2. Memory safety guarantees
Describe the specific bug classes that smart pointers eliminate through RAII, and name at least two failure modes they do not protect against.
3. Runtime cost
Quantify the overhead of each smart pointer type relative to a raw pointer. Under what conditions does std::shared_ptr become a measurable bottleneck in a multithreaded system?
Code to analyze
// Factory returning a heap-allocated resource
// Version A
Widget* makeWidget() { return new Widget(); }
// Version B
std::unique_ptr<Widget> makeWidget() { return std::make_unique<Widget>(); }
- Explain why Version B is preferred in modern C++.
- Give a concrete scenario where Version A — or a plain raw pointer — is the architecturally correct choice.
Hints
Hint 1
Think of pointer types as expressing intent: who is responsible for calling delete? Let that question guide every decision.
Hint 2
shared_ptr's reference count is atomic — trace what that means when many threads read the same pointer on separate cores.
Hint 3
C ABI boundaries, custom allocators, and parent-child ownership systems all have one thing in common: something other than your smart pointer controls the object's lifetime.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing the answer
The core question is not about API syntax — it is about making ownership visible in the type system. A strong answer covers four dimensions: what each pointer type communicates about ownership, what RAII buys you and where it stops, the concrete runtime costs, and the cases where raw pointers remain correct.
1. Ownership semantics
std::unique_ptr models exclusive ownership. It is move-only, so the compiler prevents accidental duplication of ownership. When the unique_ptr goes out of scope — regardless of whether control flow reached there via a return, a break, or a thrown exception — it calls delete on the object. Transferring ownership is an explicit, visible act: std::move(p).
std::shared_ptr models shared ownership. Every copy shares a pointer to the same control block, which holds a strong reference count, a weak reference count, a deleter, and an allocator pointer. The object is destroyed when the strong count drops to zero. The control block itself persists until the weak count also reaches zero.
A raw T* or reference T& expresses non-owning observation. The C++ Core Guidelines are unambiguous: a raw pointer never owns. Use T& when the referent is guaranteed to exist; use T* when "nothing" is a valid state or the observer needs to be reseatable.
A useful mental model for function signatures:
| Signature | Ownership intent |
|---|---|
void f(T&) / void f(T*) | Borrows; doesn't affect lifetime |
void f(std::unique_ptr<T>) | Consumes; takes sole ownership |
void f(std::unique_ptr<T>&) | May reseat the caller's pointer |
void f(std::shared_ptr<T>) | Joins the ownership group |
void f(const std::shared_ptr<T>&) | May conditionally join |
2. Memory safety
What RAII eliminates:
- Leaks on exceptional paths. Any
newunguarded by RAII leaks if an exception fires beforedelete. The smart pointer's destructor runs unconditionally. - Double-delete. Because
unique_ptrcannot be copied, two owners cannot both attempt to free the same allocation. delete/delete[]mismatches. The deleter is encoded in the type, so the correct form is always called.- Dangling observer detection.
std::weak_ptr::lock()returns null when the object is already gone, giving observers a safe way to check liveness. - Exception-safe construction.
make_uniqueandmake_sharednever leave a live allocation without an owner — a problem that can arise in certain expression evaluation orders when callingnewdirectly.
What smart pointers do not fix (interviewers notice when candidates state these):
- A raw pointer from
.get()or a reference to*pcan dangle after the owning smart pointer is destroyed. - Use-after-move: once you write
auto q = std::move(p),pis null and dereferencing it is undefined behavior. - Reference cycles between
shared_ptrinstances leak permanently. Break cycles withweak_ptr. shared_ptrmakes the reference count thread-safe, not the pointee. Concurrent mutation of the object still requires explicit synchronization.
3. Runtime cost
std::unique_ptr with the default deleter has zero overhead. Its size equals that of a raw pointer and modern compilers generate identical machine code for dereference and destruction. One subtle point: it carries a non-trivial destructor, which on the Itanium ABI (Linux, macOS) means the value is passed through memory rather than a register on some call paths. This is negligible in practice unless the pointer is passed by value on an extremely hot path. A stateful custom deleter increases object size.
std::shared_ptr carries real costs:
- Size: two pointers (object address plus control block address).
- Allocation: constructing from a raw
newexpression requires two heap allocations.make_sharedfuses them into one, at the cost of keeping the allocation alive until the lastweak_ptrdies. - Atomic operations: every copy and every destruction performs an atomic increment or decrement on the reference count.
- Extra indirection: accessing the control block is a second pointer dereference.
When shared_ptr becomes a bottleneck:
- Passing by value in tight loops adds an atomic increment on entry and decrement on exit even in single-threaded code.
- When multiple threads hold copies of the same
shared_ptr, the control block's cache line bounces between cores. This does not scale — a configuration object or market-data snapshot read by dozens of threads is a classic manifestation. - Very large object graphs with complex destruction order cause unpredictable latency spikes, and deeply linked structures can overflow the stack through recursive destructors.
Mitigations: pass const shared_ptr<T>& when you won't store the pointer; std::move instead of copying; prefer make_shared; default to unique_ptr and only escalate to shared_ptr when ownership genuinely needs to be shared.
Code comparison
#include <memory>
struct Widget { /* ... */ };
void consume(Widget& w); // observer — no ownership implied
// Version A: ownership is invisible and manual
Widget* makeWidgetRaw() { return new Widget(); }
// Version B: ownership is in the type; cleanup is automatic
std::unique_ptr<Widget> makeWidget() {
return std::make_unique<Widget>();
}
void client() {
// Version A: caller must remember to delete; any throw between
// construction and delete leaks the object
Widget* a = makeWidgetRaw();
consume(*a);
delete a;
// Version B: freed on every exit path, zero overhead
auto b = makeWidget();
consume(*b);
// Upgrading to shared ownership is trivial and explicit:
std::shared_ptr<Widget> s = makeWidget();
}
// -------------------------------------------------------
// Legitimate use of raw pointers: C ABI boundary
// -------------------------------------------------------
extern "C" {
struct Handle;
Handle* plugin_create();
void plugin_destroy(Handle*);
}
// Wrap immediately on the C++ side with a custom deleter.
// The library's own allocator must free it — shared_ptr or
// unique_ptr with the default deleter would cause a double-free.
struct PluginDeleter {
void operator()(Handle* h) const { plugin_destroy(h); }
};
using HandlePtr = std::unique_ptr<Handle, PluginDeleter>;
Why Version B is preferred: the return type self-documents that the caller now owns the object. The compiler enforces single ownership. There is no leak path. And the caller can convert it to shared_ptr without any factory change, so returning unique_ptr is strictly more flexible than returning shared_ptr directly.
Where raw pointers are the right choice:
- C ABI and plugin boundaries. C has no templates; across shared-library boundaries the allocation must be freed by the matching deallocator. Expose paired
create/destroyfunctions and wrap them with a custom-deleterunique_ptron the C++ side. - Ownership managed by an external system. Qt's parent/child tree, arena allocators, placement
newinto pre-allocated buffers, and game-engine entity systems all control their objects' lifetimes. Wrapping such an object in a standard smart pointer produces a double-free; a non-owning raw pointer is literally safer. - Back-pointers and intrusive structures. A tree node's
parentpointer, an iterator, or a doubly-linked intrusive list. The structure itself guarantees the lifetime; aT*is correct and cheap. - Inner-loop observers. Pass
T*orT&into a function that just reads data — adding a smart pointer there communicates false ownership and on theshared_ptrpath adds unnecessary atomic traffic.
Common mistakes to avoid
- Returning
shared_ptrfrom every factory "just in case" — this spreads unnecessary shared ownership and atomic overhead throughout the codebase. - Using
.get()for long-lived storage — the raw pointer can outlive the smart pointer if the caller isn't careful. - Forgetting that
shared_ptrthread-safety is limited to the count, not the object. - Creating a
shared_ptrfrom a raw pointer that is already managed elsewhere, which creates a second independent control block and causes a double-free.