我被引导理解,在移出的 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/