加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c 11 – 移动unique_ptr后,std :: unique_ptr ::返回的值是否有

发布时间:2020-12-16 04:55:21 所属栏目:百科 来源:网络整理
导读:请考虑以下代码段: class Owner {public: Owner(std::unique_ptrint ptr) : owned_pointerint(std:move(ptr)) {}private: std::unique_ptrint owned_pointer;};std::unique_ptrint ptr(new int);int* ptr1 = ptr.get();Owner new_owner(std::move(ptr)); 假
请考虑以下代码段:
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保证指向移动指针为只要它活着)?

解决方法

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

查看N3337,第20.7.1节:

  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 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.p.的unique_ptr对象.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读