(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
:
- is more efficient. It usually allocates memory for
MyClass
object and for theshared_ptr
's control block with a single memory allocation. In contrast, (2) performs at least two memory allocations. Somake_shared
reduces allocation overhead, memory fragmentation and improves locality (see GotW #89 point 2) - avoids explicit
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?).