天天看点

[modern c++] std::weak_ptr需要注意

前面讨论了 std::weak_ptr , 这里说一下使用 weak_ptr 需要注意的地方:不正确地使用weak_ptr可能会导致奔溃。

#include <memory>
#include <iostream>
#include <string>

int main(int argc,char** agev)
{
    std::weak_ptr<int> wp;
    {
    std::shared_ptr<int> sp = std::make_shared<int>(0);
    
    *sp = 10;
    
    std::cout << *sp << std::endl;
    
    wp = sp;
    }
    
    std::cout << *(wp.lock()) << std::endl; //wp指向的sp已经释放,这里会段错误
    //正确写法
    if(!wp.expired()){
        std::cout << *(wp.lock()) << std::endl;
    }
    
}