Reputation: 1263
I would like to do something like this in a class method. Basically, I have a code snippet that needs to be executed, regardless of the function returns successfully or throws an exception.
class A {
private:
int b;
public:
void foo() {
bool bar = false;
// I want this to be executed when foo returns/throws.
auto callback = [&]() {
b = bar ? 1 : 2;
}
// logic that may have return/throws.
}
};
Upvotes: 1
Views: 66
Reputation: 96810
Like ScopedGuard
referenced in rlbond's comment you can have a function_guard
which stores the callback and invokes it in its destructor:
#include <functional>
#include <type_traits>
template<class T>
struct function_guard {
template<class U, class... Args>
function_guard(U u, Args&&... args) : callback_(std::bind(u, args...)) { }
~function_guard() {
callback_();
}
private:
std::function<T> callback_;
};
Upvotes: 4
Reputation: 162
Use it similar to what std::lock_guard does it. Make an object that takes in a callback in its constructor, and then execute the callback in its destructor. e.g
class CallbackCaller{
(function pointer) ptr;
public:
CallbackCaller((function pointer) _ptr)
{
ptr = _ptr;
}
~CallbackCaller()
{
(*ptr)();
}
};
This way, when the function returns, and the object is destroyed, it will call your function pointer. You can improve this class and make it reusable by using templates! Enjoy.
Upvotes: 1