Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared_ptr assignment notation implicit conversion

considering following code , Why I can’t use the assignment notation here , Why that is considered to be an implicit conversion.

shared_ptr<string> pNico = new string("nico"); // ERROR implicit conversion
shared_ptr<string> pNico{new string("nico")};   // OK
like image 657
Adib Avatar asked Apr 01 '26 20:04

Adib


1 Answers

The constructor is explicit to prevent somebody from doing something like this:

void foo(std::shared_ptr<std::string> s) { }

int main()
{
   std::string s;
   foo(&s);
}

If it was implicit, the shared_ptr could take ownership of a stack allocated variable and try to delete it..which wouldn't make sense.

like image 138
uh oh somebody needs a pupper Avatar answered Apr 03 '26 17:04

uh oh somebody needs a pupper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!