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

I feel that the solution to both classes designed for heap allocation and binary libraries is the same: making a decent wrapper around them that obeys RAII. In many cases, this is just requires using `unique_ptr` with a custom deleter.

    auto deleter = [](unsafe_type* t) { cleanup_unsafe(t); }
    std::unique_ptr<unsafe_type, decltype(deleter)> safe(make_unsafe(), deleter);
If this is used in many places, you can make a very easy wrapper class to handle it.

    class safe_wrapper {
    public:
      safe_wrapper()
        : unsafe(make_unsafe()) { }
      ~safe_wrapper() {
        cleanup_unsafe();
      }

      unsafe_type* operator->() { return unsafe; }
    private:
      unsafe_type* unsafe;
    };
(Note that the example there is only for use within a single function. If the safe_wrapper is to be returned from a function, then the copy/move operators should be defined as needed.)

Certainly, when passing ownership back to the binary library, you are relying on it to correctly handle ownership. But so long as the ownership is in one's own code, you can easily add the type safety.

Regarding a stack-based class being accidentally placed on the heap, you can't prevent all errors, you can only make it less likely. I'd argue that it is easier to accidentally forget to call a cleanup function than it is to accidentally place something on the heap. With C++11 and up, any calls to "new" should be regarded with deep suspicion.

True on the FP patterns moving in, and I love them. `std::function` is a joy to work with, especially as compared to either C-style function pointers or inheritance from a "callable" type.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: