1

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

T {
  T(X x, Y y);
  ~T();

}
shared_ptr<T> p;
p.reset(new T(x,y));
p = make_shared<T>(t1) //t1 is a T type object

However, why this won't work?

 p = shared_ptr<T>(new T(x,y));

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?
Community
  • 1
  • 1
user3113633
  • 133
  • 1
  • 11

2 Answers2

1

However, why this won't work?

p = shared_ptr<T>(new T(x,y));

That's fine. It's used that way in the linked answer.

Converting a new expression to shared_ptr is unsafe when other subexpressions may throw exceptions. It's possible to get a memory leak, due to unspecified order of evaluation. But new as an initializer for a named variable is safe.

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

The problem is that shared_ptr requires a reference count on the heap. make_shared is able to combine the shared object and the reference count into a single allocation, whereas the conversion takes a preexisting object and therefore needs to call new again just for the count.

Community
  • 1
  • 1
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
0

Is p = shared_ptr<T>(new T()) just a bad practice or it is simply wrong?

You're confusing a NULL pointer with a pointer to a default-constructed object. Neither is "right" or "wrong"; they simply have different semantics and are appropriate in different circumstances.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Thank you for your answer, do you mind further elaborating on your answer? I think shared_ptr p; will give a null pointer while all the 3 lines following will assign an object to be managed by the pointer while I am trying to figure out the difference between the last one versus previous ones? Sorry if my concepts are completely wrong. – user3113633 Jan 04 '17 at 05:19