简体   繁体   English

我应该分配还是重置unique_ptr?

[英]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. 堆分配发生在初始化方法中,而不是在ctor中。 Therefore, I cannot use initialiser lists. 因此,我无法使用初始化列表。

From the docs of unique_ptr 's operator= : 来自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所指向的对象的所有权转移给*,就好像通过调用reset(r.release())后跟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 而你需要的只是reset调用,因此直接调用它更简单

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 reset as 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因为在这种情况下您不会创建无用的中间实例(即使机器级别可能没有差异,因为优化器可以在那里做很多事情)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM