mardi 3 janvier 2017

Assign a newly constructed shared_ptr

I encounter a question with shared_ptr, it seems that to initialize an empty shared_ptr, there are a two common ways as quoted from std::shared_ptr: reset() vs. assignment

shared_ptr<T> p;
p.reset(new T());
p = make_shared<T>(t1)

However, why this won't work?

 p = shared_ptr<T>(new T());

Is it just a bad practice or it is simply wrong? Thanks!

There is an answer saying that make_shared is more efficient than new in terms of construction Is make_shared really more efficient than new?:

std::shared_ptr<Object> p1 = std::make_shared<Object>("foo"); //copy??
std::shared_ptr<Object> p2(new Object("foo")); //conversion?

Aucun commentaire:

Enregistrer un commentaire