Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost shared_ptr: difference between operator= and reset?

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...
like image 724
rturrado Avatar asked Mar 18 '11 12:03

rturrado


People also ask

Can shared_ptr be copied?

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.

Do I need to delete a shared_ptr?

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.

What is the purpose of the shared_ptr <> template?

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.

What is boost :: shared_ptr?

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.


1 Answers

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 ...
}
like image 149
Björn Pollex Avatar answered Oct 08 '22 06:10

Björn Pollex