KatInterview

Build a Reference-Counted Smart Pointer in C++

Data Structure DesignModel answer
MediumModel answerData Structure Designc++memory-managementraii

Last updated

Design and implement a shared ownership pointer with automatic memory management using reference counting and RAII principles.

Problem

Memory safety is essential in systems code. Write a generic smart pointer template RefPtr<T> that provides shared ownership semantics: the managed resource is automatically freed when the final owner is destroyed.

Multiple RefPtr instances can point to the same object. The object persists as long as at least one RefPtr owns it, and is deleted exactly once when the last owner goes away.

Interface

Your RefPtr must support:

template<typename T>
class RefPtr {
public:
    // Takes ownership of a raw pointer (may be nullptr)
    explicit RefPtr(T* ptr = nullptr);
    
    // Cleanup
    ~RefPtr();
    
    // Copying increases reference count
    RefPtr(const RefPtr& other);
    RefPtr& operator=(const RefPtr& other);
    
    // Moving transfers ownership without changing count
    RefPtr(RefPtr&& other) noexcept;
    RefPtr& operator=(RefPtr&& other) noexcept;
    
    // Access the managed object
    T& operator*() const;
    T* operator->() const;
    T* get() const;
    
    // Query how many owners currently exist
    size_t use_count() const;
    
    // Release current resource and optionally take a new one
    void reset(T* ptr = nullptr);
};

Example Behavior

RefPtr<int> p1(new int(10));
assert(p1.use_count() == 1);
assert(*p1 == 10);

{
    RefPtr<int> p2 = p1;  // p2 shares ownership
    assert(p1.use_count() == 2);
    assert(p2.use_count() == 2);
    *p2 = 50;
}
// p2 destroyed here

assert(p1.use_count() == 1);
assert(*p1 == 50);  // modification visible through p1

p1.reset();  // releases the int
assert(p1.get() == nullptr);
assert(p1.use_count() == 0);

Constraints

  • Handle self-assignment correctly (p = p; must not corrupt state)
  • Support nullptr initialization without unnecessary allocations
  • Ensure the managed object is deleted exactly once
  • Moving should not increment or decrement the reference count
  • reset() must safely transition between different owned objects

Explain your design, implementation strategy, time and space complexity, and how you handle the key edge cases.

Hints

Hint 1

The reference count must be shared across all copies—it cannot live inside each instance

Hint 2

Use two raw pointers: one to the managed object, one to a heap-allocated counter

Hint 3

Build copy and move assignment using temporary objects and swap to handle self-assignment automatically