Should I assign or reset a unique_ptr?

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.

70373 次浏览

这样做的正确方法(您没有列出)是使用 owned的构造函数:

owner() : owned(new someObject())
{}

除此之外,我更喜欢 reset,因为在这种情况下您不会创建一个无用的中间实例(即使在机器级别上可能没有什么区别,因为优化器可以在那里做很多事情)。

来自 ABC0的 operator=的文件:

将 r 指向的对象的所有权转移到 * this,就像通过调用 reset(r.release()),然后从 std::forward<E>(r.get_deleter())进行赋值一样。

您所需要的就是 reset调用,所以直接调用它更简单