unique_ptr 何时在此 setter 上重置?

When does the unique_ptr get reset on this setter?

class A
{
    ...
    B b;
}

我传入的 unique_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();
}

在前两种情况下,unique_ptr 在函数 SetB returns 时被重置。在这两种情况下你都不会泄漏任何内存,但你所做的事情很奇怪。

第一种情况

this->b = *b;

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

第二种情况

this->b = *move(b);

行为与第一个完全相同。这次你所做的不同之处在于在 unique_ptr<B>&& 上调用 unique_ptr::operator*std::move 只是将其参数转换为右值引用)。

在这两种情况下,unique_ptr 参数保留 B 实例的所有权 SetB 最初被调用,并且它会在函数 returns 时销毁它。


您的用例看起来根本不像您应该使用 unique_ptr 的用例,您只需要一个 setter。大概是以下

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