General idea of Golang-style defer
is explained here and here.
I wonder, does STL (of C++11, C++14, ...) or maybe Boost or maybe some other library contain implementation of such a class? So I could just use it without reimplementing it in every new project.
I presented a header-only implementation of Go-style
defer
at CppCon 2014 (YouTube link); I called itAuto
. IMHO this is still far and away the best alternative out there in terms of teachability, efficiency, and absolute fool-proofness. In use, it looks like this:The implementation looks like this:
Yes, that's the entire file: just 15 lines of code! It requires C++11 or newer, and requires your compiler to support
__COUNTER__
(although you can use__LINE__
as a poor man's__COUNTER__
if you need portability to some compiler that doesn't support it). As for efficiency, I've never seen GCC or Clang generate anything other than perfect code for any use ofAuto
at-O2
or higher — it's one of those fabled "zero-cost abstractions."The original source also has a C89 version that works on GCC by exploiting some very GCC-specific attributes.
used like this:
My implementation( please add header files yourself):
Before new standard comes, I use simple RAII class for this:
Later it can be used for any things, for example:
Also, you can use Boost.ScopeExit and similar implementations.
Here's my solution, which is similar to the type you'd encounter in swift, but I don't handle any exceptions (easy enough to add if required, just use a try/catch block like in PSIAlt's solution):
It may seem clunky due to its use of vector, but it retains the behavior of swift's defer where the functions are called in reverse order:
But it's a bit more powerful than defer in that you can add deferred calls at any scope lower than your own. You just have to be careful that the lambda captured doesn't go out of scope when you use this (a bit of a flaw but not a serious one if you're careful).
I normally wouldn't use this, unless it's going to be a one-off statement. Ideally you'd wrap any resource around a new class that deallocates it when it goes out of scope, but if its top-level code with lots of resources and error handling, defer does make more sense from a code readability standpoint. You don't have to remember a bunch of new classes that really all do the same thing.
There is a proposal for
std::unique_resource_t
which will enable code likefor resources, and it defines a general
scope_exit
, which should be the same asdefer
:It will be considered for likely adoption in the Post-C++17 standard.
Here is my defer implementation, but without noexcept guarantee, I still don't think it is very good implementation.
Used like this:
Implementation: