Class GenericRAII

Class Documentation

class GenericRAII

The GenericRAII class is a simple helper class to apply the C++ RAII idiom quickly. You set 2 functions, one which is called in the constructor and another function is called in the destructor which can be useful when handling resources.

// This example leads to a console output of:
// hello world
// I am doing stuff
// goodbye
void someFunc() {
    auto raii{[](){ std::cout << "hello world\n"; },
                [](){ std::cout << "goodbye\n"; }};
    std::cout << "I am doing stuff\n";
    // raii goes out of scope here and the cleanupFunction is called in the
    // destructor
}

Public Functions

explicit GenericRAII(const std::function<void()> &cleanupFunction) noexcept

constructor which creates GenericRAII that calls only the cleanupFunction on destruction

Parameters:

cleanupFunction[in] callable which will be called in the destructor

GenericRAII(const function_ref<void()> &initFunction, const std::function<void()> &cleanupFunction) noexcept

constructor which calls initFunction and stores the cleanupFunction which will be called in the destructor

Parameters:
  • initFunction[in] callable which will be called in the constructor

  • cleanupFunction[in] callable which will be called in the destructor

~GenericRAII() noexcept

calls m_cleanupFunction callable if it was set in the constructor

GenericRAII(const GenericRAII&) = delete
GenericRAII &operator=(const GenericRAII&) = delete
GenericRAII(GenericRAII &&rhs) noexcept

move constructor which moves a generic raii object without calling the cleanupFunction

GenericRAII &operator=(GenericRAII &&rhs) noexcept

move assignment which moves a generic raii object without calling the cleanupFunction