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); },callsgrows from0to1 - while
guardexists,callsdoes not change std::is_copy_constructible_v<ScopeGuard>→false: this is how the tests check that the copy constructor is deleted and aScopeGuardcannot 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.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.