Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we cannot use "=" to shared_ptr or unique_ptr? [duplicate]

I fount the syntax got compile error.

std::shared_ptr<int> p = new int(5);

31 41 E:\temprory (delete it if u like)\1208.cpp [Error] conversion from 'int*' to non-scalar type 'std::shared_ptr<int>' requested

But it is O.K

std::shared_ptr<int> p(new int(5));

The same as unique_ptr;

But I don't know why it is prohibited.

like image 225
chang jc Avatar asked Nov 30 '22 08:11

chang jc


2 Answers

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
like image 113
songyuanyao Avatar answered Dec 05 '22 09:12

songyuanyao


C++ doesn't allow copy-initialisation of a shared_ptr from a raw pointer because shared_ptr would be too easy to end up with an accidental implicit conversion from some arbitrary raw pointer into a shared_ptr that doesn't actually manage it.

like image 36
msc Avatar answered Dec 05 '22 10:12

msc