c++ - Correct way to initialize boost::shared_ptr -
i getting started work boost::shared_ptr have searched around , see there 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 1 preferred way init/assign , why?
thank you.
(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 1 unnecessarily complex.
(2) , (3) seem similar use make_shared whenever can (i.e. when don't need custom deleter: are there downsides using make_shared create shared_ptr).
make_shared:
- is more efficient. allocates memory
myclassobject ,shared_ptr's control block single memory allocation. in contrast, (2) performs @ least 2 memory allocations.make_sharedreduces allocation overhead, memory fragmentation , improves locality (see gotw #89 point 2) - avoids explicit
new(and, @ least c++11, it's more clear:auto c(std::make_shared<myclass>());).
the main use of assignment when want copy previously-existing boost::shared_ptr, share ownership of same object.
if need take ownership of raw pointer should use reset (boost shared_ptr: difference between operator= , reset?).
Comments
Post a Comment