C++ std::weak_ptr

545 阅读1分钟
class Object {
public:
    explicit Object(int a) : test_value(a) {}

    void print_test_value() {
        std::cout << "test_value->" << test_value << std::endl;
    }
private:
    int test_value;
};

// 通过std::weak_ptr判断所指的对象是否被释放
std::shared_ptr<Object> ptr(new Object(2012));
std::thread t([weak_ptr = std::weak_ptr<Object>(ptr)] {
    sleep(2);
    // 如果weak_ptr所指向的对象被释放了,那么ptr2就为nullptr了
    auto ptr2 = weak_ptr.lock();
    if (ptr2) {
        ptr2->print_test_value();
    } else {
        std::cout << "null ptr" << std::endl;
    }
});
t.detach();
ptr.reset();