Are there any differences between the two pieces of code below? Is any of them preferable to the other?
operator=
boost::shared_ptr<Blah> foo; // foo.ptr should be NULL
foo = boost::shared_ptr<Blah>(new Blah()); // Involves creation and copy of a shared_ptr?
reset
boost::shared_ptr<Blah> foo; // foo.ptr should be NULL
foo.reset(new Blah()); // foo.ptr should point now to a new Blah object
Note: I need to define the shared_ptr and then set it in a different line because I'm using it in a piece of code like:
boost::shared_ptr<Blah> foo;
try
{
foo.reset...
}
foo...
After you initialize a shared_ptr you can copy it, pass it by value in function arguments, and assign it to other shared_ptr instances.
The purpose of shared_ptr is to manage an object that no one "person" has the right or responsibility to delete, because there could be others sharing ownership. So you shouldn't ever want to, either.
std::shared_ptr. std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object.
shared_ptr is now part of the C++11 Standard, as std::shared_ptr . Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type ( T[] or T[N] ) as the template parameter.
operator=
assigns a shared_ptr
to a shared_ptr
, while reset
makes a shared_ptr
take ownership of a pointer. So, basically there is no difference between the examples you have posted. That said, you should prefer neither of them and just use make_shared
:
foo = boost::make_shared<Blah>();
Also, if possible, you can prevent having to declare a shared_ptr
without initialization by wrapping the try-catch block in a separate function that simply returns a shared_ptr
to the newly created object:
boost::shared_ptr<Blah> createBlah() {
try {
// do stuff
return newBlah;
}
catch ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With