Search code examples
c++heap-memorysmart-pointersunique-ptrraw-pointer

How to initialize unique_ptr from raw C heap memory pointer?


I am using a function (which is part of a library) which returns a raw uint8_t* pointer to some memory which has been allocated on the heap and holds image pixel data. The caller of this function is responsible for calling free on the pointer.

My code where I call this function has many branches with early termination and I therefore would need to call free(buffer) at many points. I think it would be better if I could wrap the buffer in a unique_ptr so that when it falls out of scope, the memory is automatically freed.

How can I achieve this?

For reference, the function decleration looks something like this: uint8_t* getFrame() (I already know the width, height, and num channels of the image and thus the length of the buffer);


Solution

  • This is pretty simple to do! The template for std::unique_ptr looks like this:

    template<class T, class Deleter>
    class unique_ptr;
    

    And the Deleter is used to clean up the value pointed to by the unique_ptr when it falls out of scope. We can write one to use free really simply!

    struct DeleteByFree {
        void operator()(void* ptr) const {
            free(ptr);
        }
    };
    
    template<class T>
    using my_unique_ptr = std::unique_ptr<T, DeleteByFree>;
    

    Now, whenever you use an instance of my_unique_ptr, it'll call C's free() function to clean itself up!

    int main(){
        // This gets cleaned up through `free`
        my_unique_ptr<int> ptr {(int*)malloc(4)}; 
    }