18

I was reading about the go language's defer statement. It allows you to specify an action to take when a function has ended. For example, if you have a file pointer or resource, instead of writing free/delete with every possible return path, you just need to specify the defer function once.

It looks like an analogue might be coming to C++ eventually (What is standard defer/finalizer implementation in C++?, Will there be standardization of scope guard/scope exit idioms?) Until then, is there anything unforeseen about doing it with an object whose destructor makes a callback? It looks like the destructor order for local variables is sane and that it also handles exceptions well, though maybe not exiting on signals.

Here is a sample implementation... is there anything troubling about it?

#include <iostream>
#include <functional>
using namespace std;

class FrameExitTask {
    std::function<void()> func_;
public:
    FrameExitTask(std::function<void()> func) :
    func_(func) {
    }
    ~FrameExitTask() {
        func_();
    }
    FrameExitTask& operator=(const FrameExitTask&) = delete;
    FrameExitTask(const FrameExitTask&) = delete;
};

int main() {
    FrameExitTask outer_task([](){cout << "world!";});
    FrameExitTask inner_task([](){cout << "Hello, ";});
    if (1+1 == 2)
        return -1;
    FrameExitTask skipped_task([](){cout << "Blam";});
}

Output: Hello, world!

Community
  • 1
  • 1
daveagp
  • 2,599
  • 2
  • 20
  • 19
  • 2
    This might be more appropriate for [CodeReview](http://codereview.stackexchange.com). Note that there are already many implementations of this ScopeGuard-like class, so why reinvent the wheel? Some implementations I know have various benefits or specialized tools that I'd prefer to your version (e.g. no type erasure). – dyp Oct 10 '15 at 07:48
  • 2
    The problem with this is that each class should already do what you are doing in their destructor so the use cases in C++ are way rarer than in Go. If you are looking for existing implementations check boost.ScopeExit. Facebook's Folly has one as well I think. – Stephan Dollberg Oct 10 '15 at 08:32
  • 1
    You are probably better off marking the destructor `noexcept`. If the function you use `FrameExitTask` in returns normally, an exception from your finally handler will probably work. If the function exits due to some other exception, then a second exception from your handler is going to cause problems. – James Henstridge Oct 10 '15 at 09:43
  • `FrameExitTask`'s destructor is implicitly `noexcept`. That is, if `func_()` throws an exception, your program will be terminated. – dyp Oct 10 '15 at 15:18
  • 2
    what does it have anything to do with the `functional-programming` tag? – oblitum Oct 10 '15 at 15:59
  • Thanks to the answer mentioning ScopeGuard I found this implementation of a more general tool: http://stackoverflow.com/questions/10270328/the-simplest-and-neatest-c11-scopeguard It points out one improvement, using rvalue references and move semantics. – daveagp Oct 10 '15 at 18:27
  • inf: You're right for the example I gave here, but the application that motivated me at first does not correspond to a file or other known class. Specifically, a function does some checks then some work and when taking one of several exits, it ships the results of the work somewhere else. I could implement a single-use class but wanted to know the best general approach. – daveagp Oct 10 '15 at 18:31
  • @daveagp https://youtu.be/WjTrfoiB0MQ - video posted 8 days after your question :) – Ilya Denisov Mar 21 '20 at 18:30

3 Answers3

28

Boost discuss this in Smart Pointer Programming Techniques:

You can do, for example:

#include <memory>
#include <iostream>
#include <functional>

using namespace std;
using defer = shared_ptr<void>;    

int main() {
    defer _(nullptr, bind([]{ cout << ", World!"; }));
    cout << "Hello";
}

Or, without bind:

#include <memory>
#include <iostream>

using namespace std;
using defer = shared_ptr<void>;    

int main() {
    defer _(nullptr, [](...){ cout << ", World!"; });
    cout << "Hello";
}

You may also as well rollout your own small class for such, or make use of the reference implementation for N3830/P0052:

The C++ Core Guidelines also have a guideline which employs the gsl::finally function, for which there's an implementation here.

There are many codebases that employ similar solutions for this, hence, there's a demand for this tool.

Related SO discussion:

oblitum
  • 11,380
  • 6
  • 54
  • 120
7

This already exists, and it's called scope guard. See this fantastic talk: https://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Andrei-Alexandrescu-Systematic-Error-Handling-in-C. This lets you easily create an arbitrary callable to be called at exit. This is the newer version; it was developed originally long before go existed.

It works perfectly in general, but I'm not sure what you mean by it handling exceptions. Throwing exceptions from a function that has to be called at scope exit is a mess. The reason: when an exception is thrown (and not immediately caught), current scope exits. All destructors get run, and the exception will continue propagating. If one of the destructors throws, what do you do? You now have two live exceptions.

I suppose there are ways a language could try to deal with this, but it's very complex. In C++, it's very rare that a throwing destructor would be considered a good idea.

Nir Friedman
  • 17,108
  • 2
  • 44
  • 72
  • I meant that it correctly works when an exception is thrown mid-function, not in the callback. Finding out about ScopeGuard is very helpful. Thanks! – daveagp Oct 10 '15 at 18:19
-6

This already exists in C++, and it's a tremendously bad idea and the example you gave exemplifies why it's a pointless thing to do and I hope that the Committee never introduces it.

For example, if you have a file handle, then write a class to do it for you and then you won't have to write a defer statement for every single use case, which you could easily forget to do. Or just plain get it wrong. You write one destructor, once. That's it. Then you're guaranteed for all uses of the class that it's safe. It's much safer and much easier.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 1
    IMO there is no universal rule or tool, capable of solving any problem. I mean, talking about your suggestion with a raii wrapper, there are situations when you simply don't want to clutter your codebase with wrappers for every single adhoc acquire/release. scope_guard + lambda provides a good alternative. – Yuri Pozniak Dec 08 '18 at 16:52
  • 1
    It looks like your hopes are finally about to _not_ be fulfilled :) https://github.com/jensmaurer/papers/issues/278 – oblitum Mar 05 '19 at 20:03