Where can I find a good Scope Guard implementation for my C++ projects?

Viewed 7175

I just recently learned about Scope Guard C++ idiom. Unfortunately I can't find any good implementation of it.

Can anyone point me to some good and usable Scope Guard implementation in C++?

Thanks, Boda Cydo.

7 Answers

Let me offer a basic C++20 version.

#include <concepts>
#include <type_traits>

template <std::invocable Cleanup>
class [[nodiscard]] scope_guard
{
    Cleanup d;
public:
    scope_guard(Cleanup&& d) : d{std::forward<Cleanup>(d)} {}
    scope_guard(const scope_guard&) = delete;

    ~scope_guard(){d();}
};

// allow construction from plain function
template <typename F>
scope_guard(F&&) -> scope_guard<std::decay_t<F>>;

Please note that unless we need to move the scope_guard around, it adds zero memory overhead over Cleanup callable, because we don't need to hold it in a resettable manner, because we don't need move constructor, because we got class template argument deduction.

A fine example of how expressive the language became. Thank you commitee!

Related