Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't shared_ptr permit direct assignment

So when using shared_ptr<Type> you can write:

shared_ptr<Type> var(new Type());

I wonder why they didn't allow a much simpler and better (imo):

shared_ptr<Type> var = new Type();

Instead to achieve such functionality you need to use .reset():

shared_ptr<Type> var;
var.reset(new Type());

I am used to OpenCV Ptr class that is a smart pointer that allows direct assignment and everything works fine

like image 963
giò Avatar asked May 17 '16 12:05

giò


1 Answers

The syntax:

shared_ptr<Type> var = new Type();

Is copy initialization. This is the type of initialization used for function arguments.

If it were allowed, you could accidentally pass a plain pointer to a function taking a smart pointer. Moreover, if during maintenance, someone changed void foo(P*) to void foo(std::shared_ptr<P>) that would compile just as fine, resulting in undefined behaviour.

Since this operation is essentially taking an ownership of a plain pointer this operation has to be done explicitly. This is why the shared_ptr constructor that takes a plain pointer is made explicit - to avoid accidental implicit conversions.


The safer and more efficient alternative is:

auto var = std::make_shared<Type>();
like image 125
Maxim Egorushkin Avatar answered Sep 19 '22 19:09

Maxim Egorushkin