在移动 unique_ptr 后,指向 unique_ptr 内容的指针的内容是否有效?

D G*_*D G 6 c++ pointers unique-ptr move-semantics

我已经明白对移动的内容调用成员函数std::unique_ptr是未定义的行为。我的问题是:如果我调用.get()一个unique_ptr然后移动它,原来的.get()指针会继续指向原来的唯一指针的内容吗?

换句话说,

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

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

(“内容”可能是错误的词。我的意思是当您取消引用指针时获得的数据)

Wal*_*ter 6

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

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!
Run Code Online (Sandbox Code Playgroud)

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

std::unique_ptr<obj> p1(new obj);
std::unique_ptr<obj> p2 = std::move(p1);
p1->call_member();                          // undefined behaviour
Run Code Online (Sandbox Code Playgroud)