开发者

C++ interface between raw pointers and 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜