Skip to content
Exercise · Memory and Smart Pointers · lesson 10 of 12

Exercise: ScopeGuard

Write a class ScopeGuard that runs an action when a block ends. The constructor ScopeGuard(Callback cb, int& target) stores the function cb and the variable target, and the destructor ~ScopeGuard() calls cb(target) exactly once. Forbid copying a ScopeGuard, and add the fields yourself.

The type Callback is already declared in the file: a pointer to a function like void f(int&), called like a function. In the tests, increment adds one to its argument.

  • after the block { ScopeGuard guard(increment, calls); }, calls grows from 0 to 1
  • while guard exists, calls does not change
  • std::is_copy_constructible_v<ScopeGuard> → false

Constraints: target lives longer than the guard, and nested guards each fire when their own block ends, the inner one first.

scope_guard.cpp — cpp
cpp · 11 lines
Ctrl+Enter run · Esc leave editor