c++ - move unique_ptr 后,指向 unique_ptr 内容的指针的内容是否有效?

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

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

换句话说,

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

我想是的,但我想确定一下。

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

最佳答案

仅仅 move unique_ptr仅更改指向对象的所有权,但不会使其无效(删除)。 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!

当然,您绝不能尝试使用 unique_ptr已被移走,因为一个移自unique_ptr没有内容。因此

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

关于c++ - move unique_ptr 后,指向 unique_ptr 内容的指针的内容是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28354712/

相关文章:

C++ if(!cin) 导致循环

c++ - Qt - 如何解决 QScroller 最大尺寸限制(16777215 像素)

C 警告 : incompatible pointer types passing

c - 指针、转换和不同的编译器

在 C 中从 char * 转换为 char[31]

c++ - move 语义何时适用于 std::move?

我的教授无法弄清楚的 C++ 循环错误

c++ - Qt QException 子类抛出,但 QUnhandledException 被捕获

c++ - 我在这里使用 std::forward 还是 std::move?

c++ - std::move 之后的僵尸对象