有没有办法区分已分配(可能已过期)的weak_ptr 和未分配的。
weak_ptr<int> w1;
weak_ptr<int> w2 = ...;
我了解以下针对未转让或到期的检查,但是否有(更便宜的?)仅针对未转让的检查?
if (!w.lock()) { /* either not assigned or expired */ }
最佳答案
您可以使用两次调用 owner_before
来检查默认构造的(空)弱指针是否相等:
template <typename T>
bool is_uninitialized(std::weak_ptr<T> const& weak) {
using wt = std::weak_ptr<T>;
return !weak.owner_before(wt{}) && !wt{}.owner_before(weak);
}
这只会返回 true
如果 w{} "=="weak
,其中 "=="
比较所有者,并根据en.cppreference.com :
The order is such that two smart pointers compare equivalent only if they are both empty or if they both own the same object, even if the values of the pointers obtained by get() are different (e.g. because they point at different subobjects within the same object).
由于默认构造函数构造了一个 empty 弱指针,因此只有在 weak
也是 emptytrue >。如果 weak
已过期,这将不返回 true
。
查看生成的程序集(经过优化),这似乎非常优化:
bool is_uninitialized<int>(std::weak_ptr<int> const&):
cmp QWORD PTR [rdi+8], 0
sete al
ret
... 与检查 weak.expired()
相比:
bool check_expired(std::weak_ptr<int> const&):
mov rdx, QWORD PTR [rdi+8]
mov eax, 1
test rdx, rdx
je .L41
mov eax, DWORD PTR [rdx+8]
test eax, eax
sete al
.L41:
rep ret
... 或 returning !weak.lock()
(约 80 行组装)。
关于c++ - 如何检查weak_ptr是否为空(未分配)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45507041/