tags:

views:

100

answers:

2

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?

+5  A: 

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.

James McNellis
James McNellis never sleeps xD .
Prasoon Saurav
@Prasoon: Sleep just wastes time I could otherwise spend programming.
James McNellis
@James : Hehe, then you should read http://serendip.brynmawr.edu/exchange/node/1690 :-)
Prasoon Saurav
A: 

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.)

Gangadhar