Should I assign or reset a unique_ptr?

learnvst picture learnvst · Apr 17, 2013 · Viewed 51.5k times · Source

Given the common situation where the lifespan of an owned object is linked to its owner, I can use a unique pointer one of 2 ways . .

It can be assigned:

class owner
{
    std::unique_ptr<someObject> owned;    
public:
    owner()
    {
        owned=std::unique_ptr<someObject>(new someObject());        
    }
};

The reset method can be utilised:

class owner
{
    std::unique_ptr<someObject> owned;    
public:
    owner()
    {
        owned.reset(new someObject());
    }
};

In the interests of best practice, should I prefer one form over the other?

EDIT: Sorry folks. I over simplified this. The heap allocation occurs in an initialise method and not in the ctor. Therefore, I cannot use initialiser lists.

Answer

Kos picture Kos · Apr 17, 2013

From the docs of unique_ptr's operator=:

Transfers ownership of the object pointed to by r to *this as if by calling reset(r.release()) followed by an assignment from std::forward<E>(r.get_deleter()).

And all you need of that is the reset call, so it's simpler to just call it directly