Reputation: 93
I am just getting started to work with boost::shared_ptr
so I have searched around and I see that there are several ways of initializing it:
boost::shared_ptr<MyClass> myclass = boost::shared_ptr<MyClass>(new MyClass());
boost::shared_ptr<MyClass> myclass = new MyClass();
boost::shared_ptr<MyClass> myclass = boost::make_shared<MyClass>();
And of assigning it:
boost::shared_ptr<MyClass> someOtherType::getMyClass();
boost::shared_ptr<MyClass> myclass = someOtherTypePointer->getMyClass();
boost::shared_ptr<MyClass> myclass = boost::make_shared<MyClass>(someOtherTypePointer->getMyClass());
Which one would be the preferred way for the init/assign and why?
Thank you.
Upvotes: 6
Views: 8417
Reputation: 18902
(1) boost::shared_ptr<MyClass> c(boost::shared_ptr<MyClass>(new MyClass()));
(2) boost::shared_ptr<MyClass> c(new MyClass());
(3) boost::shared_ptr<MyClass> c(boost::make_shared<MyClass>());
The first one is unnecessarily complex.
(2) and (3) seem similar but use make_shared
whenever you can (i.e. when you don't need a custom deleter: Are there any downsides with using make_shared to create a shared_ptr).
make_shared
:
MyClass
object and for the shared_ptr
's control block with a single memory allocation. In contrast, (2) performs at least two memory allocations. So make_shared
reduces allocation overhead, memory fragmentation and improves locality (see GotW #89 point 2)new
(and, at least with C++11, it's more clear: auto c(std::make_shared<MyClass>());
).The main use of the assignment is when you want to copy a previously-existing boost::shared_ptr
, to share ownership of the same object.
If you need to take ownership of a raw pointer you should use reset
(boost shared_ptr: difference between operator= and reset?).
Upvotes: 7