How to check if weak_ptr is empty (non-assigned)?

前端 未结 3 1559
天命终不由人
天命终不由人 2021-02-18 17:29

Is there a way to distinguish between an assigned (possibly expired) weak_ptr and a non-assigned one.

weak_ptr w1;
weak_ptr w2 = ...;
         


        
3条回答
  •  抹茶落季
    2021-02-18 18:16

    You can use two calls to owner_before to check equality with a default constructed (empty) weak pointer:

    template 
    bool is_uninitialized(std::weak_ptr const& weak) {
        using wt = std::weak_ptr;
        return !weak.owner_before(wt{}) && !wt{}.owner_before(weak);
    }
    

    This will only return true if w{} "==" weak, where "==" compares owner, and according to 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).

    Since the default constructor constructs an empty weak pointer, this can only return true if weak is also empty. This will not return true if weak has expired.

    Looking at the generated assembly (with optimization), this seems pretty optimized:

    bool is_uninitialized(std::weak_ptr const&):
            cmp     QWORD PTR [rdi+8], 0
            sete    al
            ret
    

    ... compared to checking weak.expired():

    bool check_expired(std::weak_ptr 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
    

    ... or returning !weak.lock() (~80 lines of assembly).

提交回复
热议问题