ProblemsMemory ManagementImplement unique_ptr
IntermediateMemory Management

Implement unique_ptr

Context

Final interview at an HFT shop: a CTO who hasn't slept, an HR person who thinks C++ is 'like Python but older', and you. The CTO yawns: 'std::unique_ptr. Write your own. No std::.' HR nods knowingly. You have 30 minutes and a marker that's almost dry.

Task

Implement a minimal UniquePtr<T> — a move-only owning smart pointer. This is one of the most common C++ interview questions: it tests your understanding of ownership, move semantics, and the rule of five.

Constraints

  • Must be move-only: copy constructor and copy assignment deleted
  • Move must transfer ownership and null out the source
  • Destructor frees the owned object
  • release() gives up ownership without deleting
  • reset() deletes the current object and takes a new one
  • operator bool reports whether a pointer is held

Before you code

  • Why must a unique_ptr forbid copying?
  • What invariant must hold for a moved-from unique_ptr?
  • What is the difference between release() and reset()?

Tests

  • #1Dereference and get work
  • #2Move transfers ownership, source becomes null
  • #3release gives up ownership without deleting
  • #4reset deletes old object
  • #5Copying does not compile(expects compile error)

Hints

Hint 1

= delete the copy constructor and copy assignment to make it move-only.

Hint 2

Move operations steal the pointer and null the source; the destructor just deletes it.

Editorimplement-unique-ptr.cpp
Results

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