移动unique_ptr之后,指向unique_ptr内容的指针的内容是否有效? [英] Is the contents of a pointer to a unique_ptr's contents valid after the unique_ptr is moved?

查看:300
本文介绍了移动unique_ptr之后,指向unique_ptr内容的指针的内容是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被领会到,对从std::unique_ptr移出的内容调用成员函数是不确定的行为.我的问题是:如果我在unique_ptr上调用.get()然后将其移动,原始的.get()指针会继续指向原始的唯一指针的内容吗?

I've been led to understand that calling a member function on the contents of a moved-from std::unique_ptr is undefined behaviour. My question is: if I call .get() on a unique_ptr and then move it, will the original .get() pointer continue to point to the contents of the original unique pointer?

换句话说,

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

我认为可以,但是我想确定.

I think it does, but I want to make sure.

("contents"可能是错误的词.我的意思是取消引用指针时所获得的数据)

('contents' is probably the wrong word. I mean the data you get when you dereference the pointer)

推荐答案

仅移动unique_ptr仅会更改指向对象的所有权,但不会使它无效(删除).只要unique_ptr<>::get()指向的指针有效,只要它未被删除即可.例如,它将由拥有它的unique_ptr<>的析构函数将其删除.因此:

Merely moving the unique_ptr only changes the ownership on the pointed-to object, but does not invalidate (delete) it. The pointer pointed to by unique_ptr<>::get() will be valid as long as it hasn't been deleted. It will be deleted, for example, by the destructor of an owning unique_ptr<>. Thus:

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移出的unique_ptr没有内容.因此

Of course, you must never try to use a unique_ptr that has been moved from, because a moved-from unique_ptr has no contents. Thus

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

这篇关于移动unique_ptr之后,指向unique_ptr内容的指针的内容是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆