=====================测试代码======================
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
using namespace std;
class BindArgument
{
public:
BindArgument(int num)
{
this->num = num;
cout << "BindArgument:" << num << endl;
}
void foo() const
{
cout << num << endl;
}
~BindArgument()
{
cout << "~BindArgument:" << num << endl;
}
BindArgument(const BindArgument& copy)
{
num = copy.num;
cout << "copy:" << num << endl;
}
private:
int num;
};
void testBind0(BindArgument val)
{
val.foo();
}
void testBind1(const BindArgument& val)
{
val.foo();
}
void testBind2(BindArgument* val)
{
val->foo();
}
void testBind3(boost::shared_ptr<BindArgument> val)
{
val->foo();
}
int main()
{
{
BindArgument* obj = new BindArgument(0);
boost::function<void (void)> func = boost::bind(&testBind0, *obj);
delete obj;
func();
}
cout << "=====================================" << endl;
{
BindArgument* obj = new BindArgument(1);
boost::function<void (void)> func = boost::bind(&testBind1, *obj);
delete obj;
func();
}
cout << "=====================================" << endl;
{
BindArgument* obj = new BindArgument(2);
boost::function<void (void)> func = boost::bind(&testBind2, obj);
delete obj;
func();
}
cout << "=====================================" << endl;
{
boost::shared_ptr<BindArgument> obj(new BindArgument(3));
boost::function<void (void)> func = boost::bind(&testBind3, obj);
obj.reset();
func();
}
}
=============================测试结果
=============================
BindArgument:0
copy:0
copy:0
copy:0
copy:0
~BindArgument:0
~BindArgument:0
copy:0
~BindArgument:0
~BindArgument:0
copy:0
copy:0
copy:0
copy:0
copy:0
copy:0
~BindArgument:0
~BindArgument:0
~BindArgument:0
~BindArgument:0
~BindArgument:0
~BindArgument:0
~BindArgument:0
copy:0
0
~BindArgument:0
~BindArgument:0
=====================================
BindArgument:1
copy:1
copy:1
copy:1
copy:1
~BindArgument:1
~BindArgument:1
copy:1
~BindArgument:1
~BindArgument:1
copy:1
copy:1
copy:1
copy:1
copy:1
copy:1
~BindArgument:1
~BindArgument:1
~BindArgument:1
~BindArgument:1
~BindArgument:1
~BindArgument:1
~BindArgument:1
1
~BindArgument:1
=====================================
BindArgument:2
~BindArgument:2
1133176
=====================================
BindArgument:3
3
~BindArgument:3