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.
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