码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-09-09 19:53:59      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

代码:

#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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!