Automatically Shared

Further towards yesterday's traffic spiking post, another useful function that I've come up with is to_shared that converts a std::unique_ptr to a std::shared_ptr. Such a function has limited uses, in most cases you'd just use std::make_shared when you wanted a shared_ptr. But suppose you had a factory function or object that returns a unique_ptrto the created object (as it should since unique_ptr is much more flexible than a shared_ptr) but you need to capture the object in a shared_ptrvariable. You could do

auto shared = std::shared_ptr<SomeType>(factory.create());

but that has the same drawbacks that motivated the introduction of make_weak in my previous post. It would be preferable to use

auto shared = to_shared(factory.create());

This overcomes the drawbacks of the above code. It also has a brief implementation similar to make_weak:

template<typename Type_t>
std::shared_ptr<Type_t> to_shared(std::unique_ptr<Type_t>&& ptr)
{
    return std::shared_ptr<Type_t>(std::move(ptr));
}

The implementation is only marginally more complicated since unique_ptr requires the use of move semantics. I've named The function to_shared to avoid a name conflict with std::make_shared and I feel like it better describes what is going on since we're moving the object to the shared_ptr.

Advertisements

One comment

  1. […] my post the other day I off-handedly mentioned that “unique_ptr is much more flexible than shared_ptr”. No one took […]

%d bloggers like this: