mercredi 24 juin 2015

Move a unique_ptr with custom deleter to a shared_ptr

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?

Aucun commentaire:

Enregistrer un commentaire