移动unique_ptr后,由std :: unique_ptr :: get返回的值是否有效? [英] Is value returned by std::unique_ptr::get valid after moving unique_ptr?

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

问题描述

请考虑以下代码段:

class Owner {
public:
 Owner(std::unique_ptr<int> ptr) : owned_pointer<int>(std:move(ptr)) {}
private:
 std::unique_ptr<int> owned_pointer;
};


std::unique_ptr<int> ptr(new int);
int* ptr1 = ptr.get();
Owner new_owner(std::move(ptr));

只要new_owner处于范围内,就可以安全地假定ptr1有效吗?它似乎有效,但是我找不到明确指出的规范-它是未定义的行为/实现特定的对象,只是对我有用,还是上面发布的代码有效(保证ptr1指向已移动的指针,因为只要它还活着)?

Is it safe to assume that ptr1 is valid as long as new_owner stays in scope? It seems to work, but I can't find a specification that states that explicitly - is it undefined behavior/implementation specific and just happen to work for me, or the code posted above is valid (ptr1 is guaranteed to point to moved pointer as long as it stays alive)?

推荐答案

是的,C ++ 11规范保证确实将对象的所有权从一个unique_ptr转移到另一个unique_ptr不会更改对象本身的位置,并且第二个unique_ptr上的get()返回的值与传输前第一个unique_ptr上的相同.

Yes, the C++11 specification guarantees that transferring ownership of an object from one unique_ptr to another unique_ptr does not change the location of the object itself, and that get() on the second unique_ptr returns the same as it would have on the first unique_ptr before the transfer.

请参阅N3337,第20.7.1节:

Looking at N3337, section 20.7.1:

  1. 此外,u可以应要求将所有权转让给另一个唯一指针u2.转让完成后,以下内容 后置条件成立:

  1. Additionally, u can, upon request, transfer ownership to another unique pointer u2. Upon completion of such a transfer, the following postconditions hold:

  • u2.p等于预传输u.p
  • u.p等于nullptr,并且
  • 如果转移前u.d保持状态,则该状态已转移到u2.d.
  • u2.p is equal to the pre-transfer u.p,
  • u.p is equal to nullptr, and
  • if the pre-transfer u.d maintained state, such state has been transferred to u2.d.

其中,u是存储指针u.punique_ptr对象.

where u is a unique_ptr object that stores a pointer u.p.

第一个项目符号直接回答了问题,因为将get()指定为返回u.p.

The first bullet answers the question directly, since get() is specified as returning the u.p.

这篇关于移动unique_ptr后,由std :: unique_ptr :: get返回的值是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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