Quick Q: Does make_shared avoid an extra allocation for the reference counts? -- StackOverflow

A: Yes, make_shared is your friend!

Recently on SO:

What happens when using make_shared

I'm interested if these two lines of code are the same:

shared_ptr<int> sp(new int(1)); // double allocation?
shared_ptr<int> sp(make_shared<int>(1)); // just one allocation?

If this is true could someone please explain why is it only one allocation in the second line?

Add a Comment

Comments are closed.

Comments (1)

0 0

reductor said on Aug 14, 2014 05:03 PM:

For the first method using new the space allocated with new is only large enough for the int, so a second allocation must be done to store the reference count.

The second method with make_shared can allocate enough room for the reference count, and use the placement new operator internally.