ProblemsMemory ManagementRun this later
IntermediateMemory Management

Run this later

Context

Cleanup must run at the end of the scope no matter how the scope exits. In Go there is defer for this; in C++ the same is built by hand: an object remembers the callbacks, and its destructor fires them. Reverse order is essential — what was opened last closes first.

Task

Implement CallAfter — an object that collects functions via operator() and calls them when it is destroyed, in REVERSE registration order. Like defer in Go, built from a destructor.

Constraints

  • operator()(void (*f)()) registers a callback; any count, including zero
  • Callbacks run in the DESTRUCTOR, not at registration
  • Order is reverse: last registered runs first
  • An empty CallAfter destructs quietly

Before you code

  • Why is reverse order the right one for cleanup?
  • When exactly does the destructor of a local object run?
  • What real C++ idiom generalizes this object? (scope guard)

Tests

  • #1Runs at scope end, in reverse order
  • #2Empty and single-callback cases
  • #3Three callbacks, strict LIFO

Hints

Hint 1

Store the function pointers in a vector; the destructor walks it from the back.

Hint 2

Make sure nothing is called inside operator() — the test registers callbacks, checks that nothing ran yet, and only then ends the scope.

Editorcall-after-scope.cpp
Results

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