移动unique_ptr后,由std :: unique_ptr :: get返回的值是否有效? [英] Is value returned by std::unique_ptr::get valid after moving unique_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指向已移动的指针,因为只要它还活着)?
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:
-
此外,
u
可以应要求将所有权转让给另一个唯一指针u2
.转让完成后,以下内容 后置条件成立:
Additionally,
u
can, upon request, transfer ownership to another unique pointeru2
. 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-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
对象.
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屋!