C++11 bind的使用陷阱
来源:互联网 发布:软件售后工程师发展 编辑:程序博客网 时间:2024/05/21 06:49
最近使用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
0 0
- C++11 bind的使用陷阱
- 【C/C++】使用指针时的“陷阱”
- [C++] C++11 bind 的用法
- C 宏的陷阱
- std::bind绑定器、std::function、extern C的使用
- C语言指针使用陷阱
- C语言指针使用陷阱
- C/C++指针形参的使用与陷阱
- C++11中std::bind的使用
- C++11中bind的使用错误
- bind的chroot使用
- boost::bind的使用
- boost bind的使用
- boost bind的使用
- Boost.bind 的使用
- boost::bind的使用
- 使用boost的bind
- std::bind的使用
- arcgis移除黑边
- test
- UVA - 299 Train Swapping
- Linux内存管理基本概念
- github常见操作和常见错误!
- C++11 bind的使用陷阱
- TCP/IP小摘
- 第四章字符串和多维数组
- perhaps the designated entry point is not set
- 我的U3D 学习之旅
- Solve equation
- 数组去重
- 面试必会函数源代码 strcpy/memcpy/atoi/kmp/quicksort
- 第五章 树和二叉树