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: this is how the tests check that the copy constructor is deleted and a ScopeGuard cannot be copied

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

Do not add extra #include lines unless the task says so explicitly.

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

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way