News for hackers. Stuff that matters.
Re:Custom Deleters for C++ Smart Pointers by mavam on Thursday April 28, 2016 @10:22AM (#11589043)
I understand that your point is that unique_ptr facilitates resource management. But the example you provide is a misleading. How is this supposed to compile? The deleter type is part of the unique_ptr. So you need something along these lines:

     auto scope_guard = [](void*) { };
     unique_ptr<void, decltype(scope_guard)> finally{nullptr, scope_guard};
This is not very idiomatic. Something like toth mentioned makes more sense. If you want it to be efficient, use this:

    template <class Fun>
    class scope_guard {
      scope_guard() = delete;
      scope_guard(const scope_guard&) = delete;
      scope_guard& operator=(const scope_guard&) = delete;

    public:
      scope_guard(Fun f) : fun_(std::move(f)) {}

      ~scope_guard() {
        fun_();
      }

    private:
      Fun fun_;
    };

    template <class Fun>
    scope_guard<Fun> make_scope_guard(Fun f) {
      return {std::move(f)};
    }

    auto guard = make_scope_guard([] { cleanup(); });
The difference is: there's no indirection through std::function, so you save yourself a (potential) heap allocation.
Re:Custom Deleters for C++ Smart Pointers by Kristine1975 on Thursday April 28, 2016 @10:41AM (#11589194)
Facebook's Folly library implements something similar: https://github.com/facebook/folly/blob/master/folly/ScopeGua...

It provides some macros to make it easier to use, e.g.

  SCOPE_EXIT {
    cleanup();
    more_cleanup();
    if (needs_even_more_cleanup)
      even_more_cleanup();
  };
Re:Custom Deleters for C++ Smart Pointers by thrownaway2424 on Thursday April 28, 2016 @10:34AM (#11589125)
Yeah, again I am lazy and did not want to do all that typing on my phone. See https://godbolt.org/g/ywU2en for the full monty.