最近使用C++11 bind 遇到如下陷阱:
class BBB
{
public:
BBB() { _state = false; };
BBB(const BBB & b) { };
void Open(){ _state = true; };
void Close(){ _state = false;};
bool show() { return _state;};
protected:
bool _state;
};
BBB c;
function<void ()> funopen;
funopen = bind(&BBB::Open,c);
function<void ()> funclose;
funclose = bind(&BBB::Close,c);
funclose();
funopen();
cout<<c.show()<<endl;
class BBB
{
public:
BBB() { _state = false; };
BBB(const BBB & b) { };
void Open(){ _state = true; };
void Close(){ _state = false;};
bool show() { return _state;};
protected:
bool _state;
};
查阅了一下相关资料:http://www.cnblogs.com/linyilong3/p/3371339.html
在我们调用bind的时候,实际上将整个类的当前"状态"都复制了过去,因此加入拷贝构造函数进行了测试:
class BBB
{
public:
BBB() { _state = false; };
BBB(const BBB & b) { };
void Open(){ _state = true; };
void Close(){ _state = false;};
bool show() { return _state;};
protected:
bool _state;
}
果然BBB(const BBB & b) { };
在bind的时候被调用,证明当前bind的对象是实际要bind对象的副本<span style="font-family: Arial, Helvetica, sans-serif;">因此根据使用的意图,正确的用法是应该传入对象的指针:</span>
function<void ()> funopen;
funopen = bind(&BBB::Open,&c);
function<void ()> funclose;
funclose = bind(&BBB::Close,&c);
测试输出为 1