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.
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.
You can do this trick:
A a;
shared_ptr<A> pa(&a);
foo(pa);
new (&pa) shared_ptr<A>(); // pa "forgets" about a
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.
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));
}
MyType t;
nasty_function(std::shared_ptr<MyType>(&t, [](MyType*){}));