3

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
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
Adib
  • 723
  • 5
  • 22

2 Answers2

4

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.

2

Check the constructors declarations:

ie

template< class Y >
explicit shared_ptr( Y* ptr );

the explicit keyword prevents the copy initialization.

Only Converting constructors can be used on copy initialization.

xvan
  • 4,554
  • 1
  • 22
  • 37