All questions
Hard2027-08-12

Implement shared_ptr from Scratch

Company
Adobe
Role

MTS-2 (C++)

Round

Round 2 (DSA)

C++Memory ManagementOOPDesign

Problem Statement

Implement a simplified version of C++'s shared_ptr that supports:

  1. Reference counting — track how many shared_ptr instances point to the same object
  2. Automatic deletion — delete the managed object when the last shared_ptr goes out of scope
  3. Copy semantics — copying a shared_ptr increments the reference count
  4. Assignment — handle self-assignment, decrement old count, increment new count
  5. Destructor — decrement count, delete if zero

Constraints

  • Must handle copy constructor, copy assignment, and destructor correctly
  • Must not leak memory or double-free
  • Thread safety is NOT required (bonus if discussed)
  • Template-based to support any type

Expected Interface

template <typename T>
class SharedPtr {
public:
    SharedPtr(T* ptr = nullptr);
    SharedPtr(const SharedPtr& other);           // copy constructor
    SharedPtr& operator=(const SharedPtr& other); // copy assignment
    ~SharedPtr();

    T& operator*() const;
    T* operator->() const;
    int use_count() const;
};

Example

SharedPtr<int> p1(new int(42));    // count = 1
SharedPtr<int> p2 = p1;            // count = 2
SharedPtr<int> p3;
p3 = p2;                           // count = 3

// p1 goes out of scope → count = 2
// p2 goes out of scope → count = 1
// p3 goes out of scope → count = 0, memory freed

What the Interviewer Expects

  1. Separate control block — the reference count lives on the heap, shared between all copies
  2. Copy constructor — copy the pointer AND the count pointer, then increment
  3. Assignment operator — decrement old, increment new, handle self-assignment
  4. Destructor — decrement, if zero delete both the object and the control block
  5. Bonus: Discuss how weak_ptr breaks circular references

Follow-ups

  1. How would you add weak_ptr support? What changes in the control block?
  2. How would you make this thread-safe? (atomic reference count)
  3. What's the difference between shared_ptr<T>(new T) and make_shared<T>()? Why does it matter?
  4. How would you implement custom deleters?
  5. Can you demonstrate a memory leak even with shared_ptr? (circular reference)
🧠

No solution provided

Think through it. That's how you build real interview muscle.

Share: