[英]When is a `std::weak_ptr` empty?
According to [util.smartptr.weak.obs]/4 , the weak_ptr::owner_before
strict weak ordering is such that "two shared_ptr
or weak_ptr
instances are equivalent if and only if they share ownership or are both empty."根据[util.smartptr.weak.obs]/4 ,
weak_ptr::owner_before
严格的弱排序是这样的:“当且仅当它们共享所有权或均为空时,两个shared_ptr
或weak_ptr
实例是等价的。”
However, I see nothing in the standard that defines what it means for a weak_ptr
to be empty.但是,我在标准中看不到任何定义
weak_ptr
为空的含义。 Obviously a default-constructed weak_ptr
is empty, and a weak_ptr
constructed from an empty shared_ptr
is empty, but it doesn't seem to be explicitly stated whether an expired weak_ptr
is empty.显然,默认构造的
weak_ptr
是空的,而从空的shared_ptr
构造的weak_ptr
是空的,但似乎没有明确说明过期的weak_ptr
是否为空。
While I don't see it guaranteed by the Standard, usability 1 of the owner_before
ordering requires that:虽然我没有看到标准保证它,但
owner_before
订购的可用性1要求:
weak_ptr
which has become expired 2 is NOT EMPTY.weak_ptr
不是 EMPTY。 This is because only mutation of an object should change its placement in an ordering, and a weak_ptr
may expire without ever being mutated.这是因为只有 object 的突变应该改变它在排序中的位置,并且一个
weak_ptr
可能会在没有被突变的情况下过期。
1 For example, here someone has used weak_ptr
as a key in std::set
: How to compute hash of std::weak_ptr? 1例如,这里有人使用
weak_ptr
作为std::set
中的键:如何计算 std::weak_ptr 的 hash? . . Doing that, and
std::map
likewise, requires the ordering to survive expiration.这样做,以及
std::map
同样,要求订购在到期后仍然有效。 Were there to be an owner_hash
to allow use with std::unordered_set
and std::unordered_map
, that hash would also have to survive expiration.如果有一个
owner_hash
允许与std::unordered_set
和std::unordered_map
一起使用,那么 hash 也必须在到期后存活。
2 Note the subtle difference between "has become expired" and "is expired" -- a weak_ptr
constructed empty, or assigned with an empty pointer value, has expired() == true
. 2请注意“已过期”和“已过期”之间的细微差别——构造为空或分配有空指针值的
weak_ptr
已expired() == true
。 But it didn't expire (action verb), it was created in an expired state.但它没有过期(动作动词),它是在过期的 state 中创建的。 My answer only applies to
weak_ptr
values which are at some point not expired, then (passively) become expired due to detachment of shared_ptr
values from the target.我的回答仅适用于在某些时候未过期的
weak_ptr
值,然后(被动地)由于shared_ptr
值与目标的分离而过期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.