Search code examples
c++freeunique-ptr

Convert unique_ptr to void* and back, do I need to free?


In my code I use a library that has a function store_pointer accepting a void* and saving it in memory. There is then another function retrieve_pointer() that returns this void * to me, I don't have control over this library so I can't change how the function behaves.

Now I need to pass a variable to this function and get the pointer back, I have the code set up as follows:

struct Task
{
    int mId;
    Task(int id ) :mId(id)
    {
        std::cout<<"Task::Constructor"<<std::endl;
    }
    ~Task()
    {
        std::cout<<"Task::Destructor"<<std::endl;
    }
};

std::unique_ptr<Task> taskPtr(new Task(23));
store_pointer(&taskPtr);

// do stuff that doesn't involve taskPtr

Task *new_taskPtr = reinterpret_cast<Task *>(retrieve_pointer());

// do stuff with new_taskPtr pointer

Right now this all works but I wonder if the *new_taskPtr pointer needs to be deleted or if the reinterpret_cast "restores" the pointer to a unique_ptr and so the memory will be deleted automatically when it goes out of scope/the program ends.


Solution

  • std::unique_ptr<Task> taskPtr(new Task(23));
    

    When this variable goes out of scope, the dynamic allocation will be deleted. There is no need to, and you mustn't delete it yourself unless you call release on the unique pointer, which is the only way to transfer the ownership out of a unique pointer (besides transferring ownership to another unique pointer).

    Any casts that you may do have no effect on this.