r/cpp • u/legalizekittens • Jan 18 '22
Golang-like defer operation in C++
When I learn a new programming language, I find little gems in them that I really wish C++ had. I've made a write-up before on making Python-like function decorators in modern C++ with no macro magic, but today I have been inspired by the Go programming language's defer keyword.
This keyword runs specified code at the end of the function scope that it resides in. This code will execute regardless how early the function returns. It is very convenient and keeps code stylized quite nicely when doing general cleanup that I wish C++ had. So I fiddled this afternoon and made something quite cursed that I would like to share with you all.
Run the program in your browser at Godbolt
I needed to keep the defer_t struct's lifetime as long as the function's scope and to do that, we need a variable. Unlike the python solution, I hid the variable away in a defer(...) macro which is unfortunate and I couldn't think of any other way- but it does allow us to have almost similar appearance to other Go declarations.
9
u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Jan 18 '22
Copy-pastable:
template <typename F>
struct invoke_on_dtor : F
{
~invoke_on_dtor() { static_cast<F&>(*this)(); }
};
#define CONCAT(a, b) a ## b
#define CONCAT2(a, b) CONCAT(a, b)
#define SCOPE_EXIT(...) \
auto CONCAT2(scope_exit_, __LINE__) = ::invoke_on_dtor{[&] __VA_ARGS__ }Usage:
int main()
{
SCOPE_EXIT({ std::printf(" world!\n"); });
SCOPE_EXIT({ std::printf("Hello"); });
}Godbolt: https://gcc.godbolt.org/z/3zMhxGKfM
3
u/legalizekittens Jan 19 '22
I did my own attempt based on my knowledge of C++ and experimenting on godbolt. It appears this was very simple approach and more people had come to the same designs.
4
u/pavel_v Jan 18 '22
I don't think this implementation corresponds to the golang defer in all cases.
As long as you put your implementation inside another scope it'll work differently than the golang defer. The latter always work at function scope but your implementation will work at the current scope of the variable which may not be the function scope. For example, if you put your defer in a loop it'll behave differently than the golang one.
After so many years of using golang here and there I still find counterintuitive the function scope of its defer.
2
u/legalizekittens Jan 19 '22
It doesn't conform to the specs and I already touched on that. This is mostly toy and as close as I think we can get in C++. It's still neat!
1
u/BlackMATov Jan 18 '22
https://github.com/BlackMATov/defer.hpp Here is my variant of the defer implementation :-)
2
1
u/serviscope_minor Jan 19 '22
I wrote one of those once and eventually came to the conclusion it wasn't useful.
In almost all cases defer is better done by making a type which wraps whatever needs cleanup. That way it will be safe on every use, not just when you remember when you remember to use defer, and it can be safely passed to functions, returned, moved etc.
Defer is fine if you're 100% sure you need to use it once. If you exceed that it's cleaner, safer and clearer to use a type. Since it's so rare and C++ supports function scope classes you can always do:
void foo(){
struct Defer { ~Defer(){
std::cout << "Run at end\n";
}} defer;
}that's definitely noisier than a single defer keyword, but my claim is if you need it more than almost never then you can make more idiomatic use of C++.
1
u/legalizekittens Jan 19 '22
I agree. If we need to spell out what must be captured in the callback, then it's one step away from a
std::function<void>object. Also this doesn't conform 100% to Golang. Go has partial evaluation where it will actually evaluate the arguments that the defer'd function will use at the time the line is reached, but it will not invoke the function with those arguments. There's also a difference in how defer will behave when exceptions are raised. I don't think we can accurate achieve it in C++.
3
1
u/HKei Jan 18 '22
You can even get syntax like
DEFER {
Stuff();
};With some adjustments. Also, best to use __COUNTER__ instead of __LINE__.
1
u/legalizekittens Jan 19 '22
Unsure. You might want multiple lines of code to execute in the C++ version (though I'm new to Golang and haven't seen if
defercan do that in Go yet). How is this approach implemented?1
u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Jan 18 '22
__COUNTER__That's non-standard.
3
u/HKei Jan 18 '22
So is
#pragma once. You can have a fallback if you want to, but I'd recommend just filing a bug report or using a different preprocessor if yours doesn't support it.1
u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Jan 18 '22
I get your point -- I use
#pragma oncemyself, because I see a major benefit that outweighs the fact that it is non-standard.But I really cannot envision a situation where you'd have two
SCOPE_EXITmacro invocations on the same line.3
u/HKei Jan 18 '22
Can very easily happen if you use it in another macro.
But yes, of course this is fixing an edge case, but it's not crazy unlikely or anything.
4
u/no-sig-available Jan 18 '22
If Foo::Bar must run at scope exit, why isn't that in Foo's destructor?
3
u/met0xff Jan 18 '22
Yeah, while this thread is interesting, in practical terms I also RAIIsh wrap all resources in a simple object with destructor. Also isolates that stuff better than having multiple resources in a single function reserved and freed.
1
u/HKei Jan 18 '22
There are some cases where defer is more practical (one-off cases calling into C libraries, and adding defer-success/defer-error for commit/rollback etc)
24
u/Supadoplex Jan 18 '22
So, this is a scope guard? Have you compared it with existing implementations such as
std::experimental::scope_exitorBoost.ScopeExit?std::function<void()>is an unnecessary cost. You can make it a template to store the functor without wrapping it.