std::weak_ptr 每次 lock() 都会导致自身use_count自增一次

代码:

#include <memory>

#include <iostream>


int main(int argc, char*argv[]){

    std::shared_ptr<int> a(new int(1));

    std::weak_ptr<int>d(a);

    std::cout<<"d.use_count() = "<<d.use_count()<<std::endl;

    std::cout<<"a.use_count() = "<<d.use_count()<<std::endl;

    std::shared_ptr<int> b = d.lock();

    std::cout<<"d.use_count() = "<<d.use_count()<<std::endl;

    std::cout<<"a.use_count() = "<<d.use_count()<<std::endl;

    std::shared_ptr<int> c = d.lock();

    std::cout<<"d.use_count() = "<<d.use_count()<<std::endl;

    std::cout<<"a.use_count() = "<<d.use_count()<<std::endl;

    return 0;

}

编译、运行:

ongonginging@localhost :~/ongonginging/test/cpp11$ g++ --std=c++11 weak.cpp 

ongonginging@localhost :~/ongonginging/test/cpp11$ ./a.out 

d.use_count() = 1

a.use_count() = 1

d.use_count() = 2

a.use_count() = 2

d.use_count() = 3

a.use_count() = 3


你可能感兴趣的:(std::weak_ptr 每次 lock() 都会导致自身use_count自增一次)