在研究陈硕的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的拷贝构造函数,但是具体实验没有去做了。



