How do you make std::shared_ptr not call delete()

安稳与你 提交于 2019-11-29 16:04:43

问题


I have functions that take in std::shared_ptr as an argument so I am forced to use std::shared_ptr, but the object I am passing to the function is not dynamically allocated. How do I wrap the object in std::shared_ptr and have std::shared_ptr not call delete on it.


回答1:


MyType t;
nasty_function(std::shared_ptr<MyType>(&t, [](MyType*){}));



回答2:


Specify a no-op deleter when creating the shared pointer. E.g. like this:

void null_deleter(MyType *) {}

int main()
{
  MyType t;
  nasty_function(std::shared_ptr<MyType>(&t, &null_deleter));
}



回答3:


The best way to do this is to use the aliasing constructor:

nasty_function(std::shared_ptr<MyType>(std::shared_ptr<MyType>{}, &t));

Compared to the null deleter approach, this doesn't need to allocate a control block, and is noexcept.

As noted by @Casey and @Nevin, this should only be done when you are sure that the function won't attempt to take shared ownership, or if the object would outlive everything that might "own" it.




回答4:


You can do this trick:

A a;
shared_ptr<A> pa(&a);
foo(pa);
new (&pa) shared_ptr<A>();  // pa "forgets" about a



回答5:


i was just searching for a solution, saw this question. found nothing and made a great one this is my code

class HBitmap : public shared_ptr<HBITMAP__>
{
public:
    HBitmap();
    HBitmap(HBITMAP Handle);
    bool autoDelete = true;
};

Win32::HBitmap::HBitmap(HBITMAP Handle)
: shared_ptr<HBITMAP__>(Handle, [&](HBITMAP hBitmap)  {if(autoDelete)DeleteObject(hBitmap);})
{
}

this solution is a combination of lambda expressions and inheritance. very well formed. fast. you can't expect anything more. not only you can set the deleter, but if you do some modifications, you can use a std::function<void(pointer)> as a custom deleter. with lambdas you can run free and do what ever you want.



来源:https://stackoverflow.com/questions/20131877/how-do-you-make-stdshared-ptr-not-call-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!