p = new int(5); 31 41 E:\temprory ...">

Why can't we use "=" for shared_ptr or unique_ptr?

I got a syntax compilation 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 OK

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

The same as unique_ptr;

But I do not know why this is prohibited.

+4
source share
3 answers

Constructor std::shared_ptrand std::unique_ptrusing raw pointer explicit; std::shared_ptr<int> p = new int(5); copy initialization that does not take into account constructors explicit.

Copy-initialization is less permissive than direct initialization: explicit constructors do not translate constructors and are not considered for copy initialization.

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

explicit?

. .

void foo(std::unique_ptr<int> p) { ... }

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
+12

++ shared_ptr , shared_ptr shared_ptr, .

+5

Imagine if you accidentally passed in the pointer int *that you had for the function that you took std::shared_ptr<int>. When the function is completed, the pointer will be freed. If you really want to transfer ownership, you must state this explicitly.

+4
source

Source: https://habr.com/ru/post/1690422/


All Articles