Reputation: 2424
Apart of the size of generated code, what's the difference between using reset()
for initializing a shared pointer over the function make_shared()
?
Case 1 by using reset()
boost::shared_ptr<A> pA;
pA.reset(new A());
Case 2 by using make_shared()
boost::shared_ptr<A> pA;
pA = boost::make_shared<A>();
In general, is it a good practice to use reset
over make_shared
to reduce the size of executable?
Upvotes: 6
Views: 3421
Reputation: 1811
reset(new T(...))
allocates a heap block, constructs the object, allocates a new heap block for the reference counter and initializes the reference counter.
make_shared<T>(...)
allocates a heap block slightly larger than required for the object and constructs the object and the reference counter in the same heap block.
The chance is high that make_shared()
runs faster and requires less memory.
But there is a small drawback if you are using an IDE like Microsoft Visual Studio: Intellisense is not able to show you the names of the parameters used in the constructor. The code is working correctly but editing the make_shared()
call is uncomfortable.
Upvotes: 12
Reputation: 1621
make_shared<T>
creates the reference counter in the same chunk of memory which is allocated for T. It's an optimization. reset
does not do this.
Upvotes: 4