Skip to content

Source · fairmq/tools/

Exceptions.hpublic header

Defines class fair::mq::tools::CallOnDestruction.

fairmq/tools/Exceptions.h54 lines · C++API: CallOnDestructionGitHub ↗
1/********************************************************************************2 *    Copyright (C) 2021 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH    *3 *                                                                              *4 *              This software is distributed under the terms of the             *5 *              GNU Lesser General Public Licence (LGPL) version 3,             *6 *                  copied verbatim in the file "LICENSE"                       *7 ********************************************************************************/8 9#ifndef FAIR_MQ_TOOLS_EXCEPTIONS_H10#define FAIR_MQ_TOOLS_EXCEPTIONS_H11 12#include <functional>13 14namespace fair::mq::tools15{16 17/**18 * Executes the given callback in the destructor.19 * Can be used to execute something in case of an exception when catch is undesirable, e.g.:20 *21 * {22 *    // callback will be executed only if f throws an exception23 *    CallOnDestruction cod([](){ cout << "exception was thrown"; }, true);24 *    f();25 *    cod.disable();26 * }27 */28 29class CallOnDestruction30{31  public:32    CallOnDestruction(std::function<void()> c, bool enable = true)33        : callback(c)34        , enabled(enable)35    {}36 37    ~CallOnDestruction()38    {39        if (enabled) {40            callback();41        }42    }43 44    void enable() { enabled = true; }45    void disable() { enabled = false; }46 47  private:48    std::function<void()> callback;49    bool enabled;50};51 52} // namespace fair::mq::tools53 54#endif /* FAIR_MQ_TOOLS_EXCEPTIONS_H */