Convert a std::unique_ptr into a std::shared_ptr.

Synopsis

Declared in <absl/memory/memory.h>

template<
    typename T,
    typename D>
std::shared_ptr<T>
ShareUniquePtr(std::unique_ptr<T, D>&& ptr);

Description

Adopts a std::unique_ptr rvalue and returns a std::shared_ptr of deduced type. Ownership (if any) of the held value is transferred to the returned shared pointer.

Example:

auto up = std::make_unique<int>(10); auto sp = absl::ShareUniquePtr(std::move(up)); // shared_ptr<int> CHECK_EQ(*sp, 10); CHECK(up == nullptr);

Note that this conversion is correct even when T is an array type, and more generally it works for any deleter of the unique_ptr (single‐object deleter, array deleter, or any custom deleter), since the deleter is adopted by the shared pointer as well. The deleter is copied (unless it is a reference).

Implements the resolution of LWG 2415, by which a null shared pointer does not attempt to call the deleter.

Return Value

A std::shared_ptr adopting the value held by ptr.

Parameters

Name

Description

ptr

The unique pointer to convert; its ownership is transferred.

Created with MrDocs