c++ – Why does shared_ptr disallow implicit pointer conversion?


This code doesn't compile:

std::shared_ptr<MyType> pi = new MyType[5];

Instead, since the shared_ptr constructor is declared explicit , you have to write:

std::shared_ptr<MyType> pi(new MyType[5]);

I find it inconvenient to say the least.

What are the reasons for this design?

And what is the benefit from this?


Let's say we have a function that accepts a smart pointer:

void foo(std::shared_ptr<Mytype> data){

Then this code will lead to the removal of the resource, although we did not mean it:

MyType *object = new MyType();

When the function is called, a smart pointer will be created, and when it exits, it will delete the object it owned. And it will compile without any warnings.

Scroll to Top