c++ - 如何检查weak_ptr是否为空(未分配)?

标签 c++ c++11 weak-ptr

有没有办法区分已分配(可能已过期)的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/

相关文章:

c++ - 当矩阵没有 LU 分解时,如何在 C++ 中求解方阵的线性系统?

c++ - 如何在 C++11 中模拟没有 lambda 表达式的嵌套函数?

c++ - 我怎样才能用智能指针做到这一点?

c++ - 如何保持常量正确性和 RAII?

c++ - 从原始指针创建 weak_ptr<>

c++ - Qt 中的错误消息和更好组织的代码

c++ - 可以将一个空插入另一个集合吗?

c++ - 减少 C++ 中 double 的范围

c++ - 区分模板类构造函数中的 1D 和 2D 容器 (SFINAE)

c++ - 与成员函数中的 std::move(*this) 的行为差异