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?
There is also a potential subtle bug: in
sp(new int)
you fist allocate an int (whose pointer is given tosp
), than sp itself has to allocate a control block (will contain the counters and the deleter).Now, if doing this last allocation
sp
fails (low memory) you are left with a heap allocated int whose pointer is not held by anyone, and thus impossible to delete. (memory leak).The first case does not perform a double allocation, it performs two allocations, one for the managed object and one for the control block of the
shared_ptr
.For the second case, cppreference has a good explanation for why std::make_shared usually only performs one memory allocation it says (emphasis mine going forward):
and from std::shared_ptr section it says:
This
make_shared
description is consistent with the C++11 draft standard which says in section20.7.2.2.6
shared_ptr creationHerb Sutter has a more detailed explanation of the advantages of using
make_shared
in GotW #89 Solution: Smart Pointers and points out some advantages:Be aware that when using std::weak_ptr using make_shared has some disadvantages.
Explanation from cppreference std::shared_ptr in
Implementation notes
section