Answer the question
In order to leave comments, you need to log in
How to execute some code on function exit?
Suppose I have several exit points (return) from the function and it is necessary to execute some code when exiting the function. You can extract this code into a function, but you can forget to call it. I don't want to use goto.
Is there a ready-made solution in C++ for such cases? I would like something very simple like:
void function() {
run_at_return([]{ /*do something */ });
//...
if (condition) {
return;
}
//...
if (condition2){
return;
}
}
Answer the question
In order to leave comments, you need to log in
You can use a destructor. Don't forget that you can't throw exceptions in the destructor.
#include <iostream>
#include <functional>
template <typename T>
class defer {
private:
std::function<T()> mFunctor;
public:
defer(std::function<T()> functor) : mFunctor(functor) {}
~defer() { mFunctor(); }
};
int main() {
defer<void> d([] { std::cout << "Deferred func!" << std::endl; });
//...
std::cout << "Hello, world!" << std::endl;
if (true) {
return 0;
}
//...
if (false){
return 1;
}
return 0;
}
...
auto f = []{ cout << "asdf"; };
...
class invoker
{
public:
~invoker()
{
fn();
}
decltype(f) fn = f;
};
invoker c;
...
Not a question (C++17, convolution):
template<typename... Funcs>
auto compose_sq(Funcs&&... funcs)
{
return [=]{ (std::invoke(funcs), ...); };
}
int main()
{
auto f1 = []{ std::cout << "f1" << std::endl; };
auto f2 = []{ std::cout << "f2" << std::endl; };
auto f3 = compose_sq(f1, f2);
f3();
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question