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

前端 未结 3 1558
天命终不由人
天命终不由人 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:24

    You could try to create a shared pointer that accepts a weak pointer as a parameter and raises a std::bad_weak_ptr exception if a weak pointer is expired (or not assigned as in your case):

    #include 
    #include 
    int main(){
        // with an assigned pointer
        std::shared_ptr p1(new int(42));
        std::weak_ptr w1(p1);
        try {
            std::shared_ptr p2(w1);
        }
        catch (const std::bad_weak_ptr& e) {
            std::cout << e.what() << '\n';
        }
        // with a non assigned pointer
        std::shared_ptr p2(new int(42));
        std::weak_ptr w2;
        try {
            std::shared_ptr p2(w2); // raises an exception
        }
        catch (const std::bad_weak_ptr& e) {
            std::cout << "Ptr 2: " << e.what() << '\n';
        }
    }
    

提交回复
热议问题