KatInterview

Raw Pointers vs Smart Pointers: Ownership, Safety, and Cost

System DesignModel answer
HardModel answerSystem DesignC++memory-managementRAII

Last 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.