C++ 我应该分配还是重置unique_ptr?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16061407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:03:01  来源:igfitidea点击:

Should I assign or reset a unique_ptr?

c++c++11smart-pointersunique-ptr

提问by learnvst

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.

编辑:抱歉各位。我过度简化了这一点。堆分配发生在初始化方法中,而不是在构造函数中。因此,我不能使用初始化列表。

采纳答案by Kos

From the docs of unique_ptr's operator=:

来自's的文档unique_ptroperator=

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()).

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

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

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

回答by filmor

The proper way to do this (that you didn't list) is to use the constructor of owned:

执行此操作的正确方法(您没有列出)是使用以下构造函数owned

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

Apart from that I'd prefer resetas you don't create a useless intermediate instance in that case (even though there might be no difference on the machine level as the optimizer can do a lot there).

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