gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:58:10 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com