ProblemsMemory ManagementImplement shared_ptr
AdvancedMemory Management

Implement shared_ptr

Context

Round two of the same interview. The CTO finishes his third espresso: 'Okay, unique_ptr was the warm-up. Now shared_ptr — with a working reference count.' HR writes 'shared pointer = candidate strength' in her notebook. Don't let her down.

Task

Implement a minimal SharedPtr<T> with reference counting. Copies share ownership; the managed object is deleted only when the last SharedPtr goes away.

Constraints

  • Maintain a shared reference count on the heap
  • Copy increments the count; destruction decrements it
  • Delete the object and the counter when the count hits zero
  • use_count() returns the current number of owners
  • Move must not change the total count (it transfers, not duplicates)

Before you code

  • Where does the reference count live, and why on the heap?
  • What must operator= do before overwriting its current state?
  • How do you avoid a double-free when count reaches zero?

Tests

  • #1use_count is 1 after construction
  • #2Copy increments, scope exit decrements
  • #3Object deleted when last owner dies
  • #4Assignment rebinds and counts correctly

Hints

Hint 1

Store both the object pointer and a heap-allocated size_t* count.

Hint 2

Copy increments *count; destructor decrements it and frees both when it hits zero.

Editorimplement-shared-ptr.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.