请考虑以下代码段:
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节:
Additionally,
u
can,upon request,transfer ownership to another unique pointeru2
. Upon completion of such a transfer,the following
postconditions hold:
u2.p
is equal to the pre-transferu.p
,u.p
is equal tonullptr
,and- if the pre-transfer
u.d
maintained state,such state has been transferred tou2.d
.
其中u是存储指针u.p.的unique_ptr对象.
第一个项目符号直接回答问题,因为get()被指定为返回u.p.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。