I have a function which creates a unique_ptr with a custom deleter and returns it:
auto give_unique_ptr() {
auto deleter = [](int* pi) {
delete pi;
};
int* i = new int{1234};
return std::unique_ptr<int, decltype(deleter)>(i, deleter);
}
In the client code of that function, I'd like to move the unique_ptr
into a shared_ptr
, but I don't know how to do that given that I don't know the decltype of my custom deleter outside of the function.
I guess it should look something like this:
auto uniquePtr = give_unique_ptr();
auto sharedPtr = std::shared_ptr<..??..>(std::move(uniquePtr));
What do I have to write instead of ..??.. to get the correct type?
If this is possible, will the shared_ptr
behave nicely and call my custom deleter created inside the give_unique_ptr()
function when it's usage count reaches zero?
If you know (or want to explicitly type) the type of the object, then you can do this:
The constructor of
std::shared_ptr
will take care of the deletor.If you, however, want the type to be inferred, then:
where
make_shared_from
is:Hope that helps.