【问题标题】:Is the contents of a pointer to a unique_ptr's contents valid after the unique_ptr is moved?在移动 unique_ptr 后,指向 unique_ptr 内容的指针的内容是否有效?
【发布时间】:2015-02-05 21:48:27
【问题描述】:

我被引导理解,对已移动的 std::unique_ptr 的内容调用成员函数是未定义的行为。我的问题是:如果我在 unique_ptr 上调用 .get() 并 然后 移动它,原来的 .get() 指针会继续指向原始唯一指针的内容吗?

换句话说,

std::unique_ptr<A> a = ...
A* a_ptr = a.get();
std::unique_ptr<A> a2 = std::move(a);
// Does *a_ptr == *a2?

我认为确实如此,但我想确定一下。

('contents' 可能是错误的词。我的意思是当你取消引用指针时得到的数据)

【问题讨论】:

  • 该指针后面的对象没有被破坏。并且对象的地址不能改变。因此,您拥有的地址必须仍然有效。
  • @drescherjm 不,移动后,第一个 unique_ptr 不拥有任何东西。
  • 我现在明白了。我错误地认为在移动中使用了 a_ptr(这对我来说没有意义 - 必须仔细阅读)。

标签: c++ pointers move-semantics unique-ptr


【解决方案1】:

仅移动unique_ptr 只会更改指向对象的所有权,但不会使其无效(删除)。 unique_ptr&lt;&gt;::get() 指向的指针只要没有被删除就有效。例如,它将被拥有的unique_ptr&lt;&gt; 的析构函数删除。因此:

obj*ptr = nullptr;                          // an observing pointer
{ 
  std::unique_ptr<obj> p1;
  {
    std::unique_ptr<obj> p2(new obj);       // p2 is owner
    ptr = p2.get();                         // ptr is copy of contents of p2
    /* ... */                               // ptr is valid 
    p1 = std::move(p2);                     // p1 becomes new owner
    /* ... */                               // ptr is valid but p2-> is not
  }                                         // p2 destroyed: no effect on ptr
  /* ... */                                 // ptr still valid
}                                           // p1 destroyed: object deleted
/* ... */                                   // ptr invalid!

当然,您绝不能尝试使用已被移出的unique_ptr,因为已被移出的unique_ptr 没有内容。因此

std::unique_ptr<obj> p1(new obj);
std::unique_ptr<obj> p2 = std::move(p1);
p1->call_member();                          // undefined behaviour

【讨论】:

  • 我们是否应该延长警告,即不能使用 unique_ptr 的原始指针,因为接收到移动指针的实体可能会破坏它,所以它也被移动了?
  • @Zoso 存储unique_ptr::get() 返回的指针以供以后使用无论如何都是一个坏主意(移动unique_ptr 并不是使存储的指针失效的唯一方法)。
猜你喜欢
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多