Hacker News new | past | comments | ask | show | jobs | submit login

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/ebe7ebfd855a95eb937831...




Of 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).


> 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 :)




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: