Adopt ownership of a raw pointer into a std::unique_ptr.
Synopsis
Declared in <absl/memory/memory.h>
template<typename T>
std::unique_ptr<T>
WrapUnique(T* ptr);
Description
Adopts ownership from a raw pointer and transfers it to the returned std::unique_ptr, whose type is deduced. Because of this deduction, do not specify the template type T when calling WrapUnique.
Example: X* NewX(int, int); auto x = WrapUnique(NewX(1, 2)); // 'x' is std::unique_ptr<X>.
Do not call WrapUnique with an explicit type, as in WrapUnique<X>(NewX(1, 2)). The purpose of WrapUnique is to automatically deduce the pointer type. If you wish to make the type explicit, just use std::unique_ptr directly.
auto x = std::unique_ptr<X>(NewX(1, 2));
-
or ‐ std::unique_ptr<X> x(NewX(1, 2));
While absl::WrapUnique is useful for capturing the output of a raw pointer factory, prefer 'std::make_unique<T>(args...)' over 'absl::WrapUnique(new T(args...))'.
auto x = WrapUnique(new X(1, 2)); // works, but nonideal. auto x = make_unique<X>(1, 2); // safer, standard, avoids raw 'new'.
Note that absl::WrapUnique(p) is valid only if delete p is a valid expression. In particular, absl::WrapUnique() cannot wrap pointers to arrays, functions or void, and it must not be used to capture pointers obtained from array‐new expressions (even though that would compile!).
Return Value
A std::unique_ptr owning ptr.
Parameters
Name |
Description |
ptr |
The raw pointer to take ownership of. |
Created with MrDocs