2 ms·
I know that's not directly what you're asking for, but I found the other day that "C++ Core Guidelines" have a helper library "GSL_util" that provide something
by dgellow 7y ago
I know that's not directly what you're asking for, but I found the other day that "C++ Core Guidelines" have a helper library "GSL_util" that provide something similar to Go's defer.
The implementation is very simple, it's just using a class for its destructor:
template <class F>
class final_act
{
public:
explicit final_act(F f) noexcept : f_(std::move(f)), invoke_(true) {}
final_act(final_act&& other) noexcept : f_(std::move(other.f_)), invoke_(other.invoke_)
{
other.invoke_ = false;
}
final_act(const final_act&) = delete;
final_act& operator=(const final_act&) = delete;
~final_act() noexcept
{
if (invoke_) f_();
}
private:
F f_;
bool invoke_;
};
Source: https://github.com/microsoft/GSL/blob/ebe7ebfd855a95eb93783164ffb342dbd85cbc27/include/gsl/gsl_util#L53-L89 https://github.com/microsoft/GSL/blob/ebe7ebfd855a95eb937831...
- saagarjha 7y agoOf course, in C++ the need for such constructs is reduced due to RAII and scoping running destructors automatically. This is useful when you need to interact with C libraries that you don’t want to wrap in C++ (and when I was doing something like this in the past, I rolled my own as well).
- dgellow 7y ago> This is useful when you need to interact with C libraries that you don’t want to wrap in C++ Yep! I really like the defer pattern for those situations :)