[英]Is the contents of a pointer to a unique_ptr's contents valid after the unique_ptr is moved?
我被引导理解对从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?
我认为可以,但是我想确定。
(“内容”可能是错误的词。我的意思是取消引用指针时所获得的数据)
仅移动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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.