Search code examples
c++memory-managementshared-ptrsmart-pointers

shared_ptr with given C-like allocation and deallocation functions


I was given an API for some library (nng to be exact) it has a C-like interface for allocating and deallocating a message object:

int nng_msg_alloc(nng_msg **, size_t);
void nng_msg_free(nng_msg *);

I'm trying to create a C++ interface for the library. I would like to create a shared_ptr of a nng_msg object, but I'm struggling with the implementation. How do i pass the allocator and deallocator to the shared object?


Solution

  • You only have to pass the allocated pointer and the custom deleter to std::shared_ptr, for example:

    std::shared_ptr<nng_msg> new_nng_msg(std::size_t size) {
        nng_msg* ptr;
        auto res = nng_msg_alloc(&ptr, size);
    
        // example error handling, adjust as appropriate
        if(res != 0)
            throw std::bad_alloc{};
    
        return {ptr, nng_msg_free};
    }