S
S
SerJook2018-11-28 18:17:00
C++ / C#
SerJook, 2018-11-28 18:17:00

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

3 answer(s)
A
Alexander Movchan, 2018-11-28
@SerJook

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;
}

V
Victor Vakhturov, 2018-11-28
@xxx3Vxxx

...
auto f = []{ cout << "asdf"; };
...
class invoker
{
public:
    ~invoker()
    {
        fn();
    }
    decltype(f) fn = f;
};

    invoker c;
...

Written from my phone, sorry if there are any typos.

V
Vitaly, 2018-11-28
@vt4a2h

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;
}

Well, if you need to save the result of returning the value of the first function, then you have to write a little more code. I think that the general direction is clear to you. If anything, additional information can be found here: https://en.cppreference.com/w/cpp/language/fold

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question