标签:
代码:
#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自增一次
标签:
原文地址:http://my.oschina.net/u/1176097/blog/503940