user3811839
user3811839

Reputation: 141

What stops compilers from automatically deducing to use make_shared?

I understand:

shared_ptr<X> x = make_shared<X>();

is more efficient than:

shared_ptr<X> x(new X());

and I understand the advantages. However, I do not understand why the compiler could not have a rule like

"if I see new() in the same line as a shared_ptr declaration, use make_shared"

So what is it which stops compilers from automatically using make_shared and instead requiring us to specify it?

Upvotes: 3

Views: 130

Answers (1)

odinthenerd
odinthenerd

Reputation: 5552

It probably could be done, but adding another special rule just to save typing is not effective and not the philosophy of c++, what if someone were to come up with a better shared_ptr, if std::shared_ptr is a template then just make a better_shared template and you done. If it gets into the core language though its there for good.

Also note that it wouldn't save much typing:

auto x = make_shared<X>() vs shared_ptr<X> x(new X())

It would also be more complicated than "if I see new() and a shared pointer then use make_shared" because make_shared only replaces one of the 13 (I think) overloads of a shared_ptr constructor. The rules would undoubtedly be pages long in the standard which is big enough already. Just use make_shared and then you don't need the extra rule.

Upvotes: 1

Related Questions