The constructor of std::shared_ptr
and std::unique_ptr
taking raw pointer are explicit
; std::shared_ptr<int> p = new int(5);
is copy initialization, which doesn't consider explicit
constructors.
Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.
For direct initialization, explicit
constructors are considered then std::shared_ptr<int> p(new int(5));
works fine.
Why the constructor is explicit
?
To prevent unintentional implicit conversion and ownership transfer. e.g.
void foo(std::unique_ptr<int> p) { ... }
then
int* pi = new int(5);
foo(pi); // if implicit conversion is allowed, the ownership will be transfered to the parameter p
// then when get out of foo pi is destroyed, and can't be used again