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

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

    Using std::weak_ptr::expired()

    #include 
    #include 
    
    //declare a weak pointer
    std::weak_ptr gw;
    
    void f()
    {
        //check if expired
        if (!gw.expired()) {
            std::cout << "pointer is valid\n";
        }
        else {
            std::cout << "pointer  is expired\n";
        }
    }
    
    int main()
    {
        f();
        {
            auto cre = std::make_shared(89);
            gw = cre;
            f();
        } 
    
        f();
    }
    

    Output

    pointer  is expired
    pointer is valid
    pointer  is expired
    Program ended with exit code: 0
    

提交回复
热议问题