唯一_ptr何时在此设置器上重置


class A
{
    ...
    B b;
}

我何时删除了唯一的_ptr?

void A::SetB( unique_ptr<B> b )
{
    this->b = *b;
} // At end of scope, is `b` now reset 
  // and the `B b` in class `A` just stores the value in it?

如果以上答案是否,则不会被删除...这会删除它:

void A::SetB( unique_ptr<B> b )
{
    this->b = *move(b);
} // At end of scope, is `b` now reset
  // and the `B b` in class `A` just stores the value in it?

,如果我希望在此时将其删除,则必须自己重置:

void A::SetB( unique_ptr<B> b )
{
    this->b = *b;
    b.reset();
}

在前两种情况下,当功能SetB返回时,unique_ptr将重置。无论哪种情况,您都不会泄漏任何内存,但是您正在做的是奇怪的。

在第一种情况下

this->b = *b;

unique_ptr::operator*返回对托管对象的引用。因此,您将unique_ptr<B>参数中包含的B实例分配给您的类'数据成员b

第二种情况

this->b = *move(b);

行为与第一个完全相同。这次您所做的所有您所做的一切都是在unique_ptr<B>&&上调用unique_ptr::operator*std::move只需将其参数投入到RVALUE参考)。

在这两种情况下,unique_ptr参数保留了B实例SetB的所有权,最初是调用的,当功能返回时,它将破坏它。


您的用例似乎根本不应该使用unique_ptr,您所需要的只是一个设置器。可能是以下

void A::SetB( B b )
{
    this->b = move(b);
}

最新更新