Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ interface between raw pointers and shared_ptr

Tags:

c++

shared-ptr

I have code that uses raw pointers throughout.

It needs to call a method that takes the raw pointer into a shared_ptr. This method is not under my control, belonging to an external api. I cannot just pass the pointer to the shared_ptr because when it will be deleted when the shared_ptr goes out of scope in the method (when the method returns).

Do I have any option other than making my raw pointer a shared_ptr in my internal code?

like image 457
user231536 Avatar asked Dec 16 '22 22:12

user231536


2 Answers

This sounds somewhat unusual and potentially quite dangerous, but you can accomplish this by using a no-op deleter when constructing the shared_ptr:

struct no_op_delete
{
    void operator()(void*) { }
};

int* p = 0; // your pointer
std::shared_ptr<int> sp(p, no_op_delete());

When sp and all copies that were made of it have been destroyed, no_op_delete will be invoked to clean up the held pointer. Since it does nothing, you get the behavior you need.

like image 60
James McNellis Avatar answered Dec 24 '22 01:12

James McNellis


James had already answered the question. So, this is merely a suggestion. If you know that the function call doesn't modify the object (like setting some data members etc.), you could create a new object from your raw pointer and pass that via a shared_ptr to the function. That way, you assume that the function takes ownership of the object and does whatever is required. Of course this doesn't work if the function will modify the object in it. This can work if the function uses the object as a read-only to do some other operation (like file I/O for e.g.)

like image 40
Gangadhar Avatar answered Dec 24 '22 02:12

Gangadhar