栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ std::bind会增加智能指针shared

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ std::bind会增加智能指针shared

问题描述

在研究陈硕的muduo源码时候,发现经常看到将用户函数和智能指针参数通过std::bind绑定到回调函数里使用,于是奇怪这样会不会增加智能指针shared_ptr的计数。然后我做了一下实验,先说结论:
std::bind会增加智能指针shared_ptr计数。

代码如下:

#include 
#include 
#include 

using namespace std;

class Testbind : public enable_shared_from_this {
public:
    shared_ptr get_ptr() {
        return shared_from_this(); //返回一个智能指针
    }

    void testfun() { //用户函数

    }
};


function callback; //回调函数


int main() {
    shared_ptr testb = make_shared();
    cout << testb.use_count() << endl; //打印1
    auto anotherptr = testb->get_ptr();
    cout << testb.use_count() << endl; //打印2
    callback = bind(&Testbind::testfun, testb); //绑定用户函数和智能指针到回调函数上
    cout << testb.use_count() << endl; //打印3
    callback = NULL;
    cout << testb.use_count() << endl; //打印2
    return 0;
}
原因分析

std::bind估计调用了shared_ptr的拷贝构造函数,但是具体实验没有去做了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001624.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号