求问c++11中function绑定类成员变量的问题

zeqi1991 2019-03-19 11:14:37

#include <iostream>
#include <functional>
#include <string>

using namespace std;

class Foo
{
public:
Foo();
~Foo();
Foo(const Foo& other);
Foo& operator = (const Foo& other);
public:
void methodA();
void methodB(int num);
void methodC(string& name);
private:
int number_;
};

Foo::Foo()
{
number_ = 0;
}

Foo::~Foo()
{
number_ = 100;
}

Foo::Foo(const Foo& other)
{
number_ = other.number_;
}

Foo& Foo::operator = (const Foo& other)
{
if (this == &other)
return *this;
number_ = other.number_;
return *this;
}

void Foo::methodA()
{
cout << __FUNCTION__ << endl;
number_ = 1000;
}

void Foo::methodB(int num)
{
cout << __FUNCTION__ << endl;
number_ = 1000;
cout << number_ + num << endl;
}

void Foo::methodC(string& name)
{
cout << __FUNCTION__ << endl;
cout << name << endl;
number_ = 1000;
cout << number_ << endl;
}

std::function<void()> functor;

int main()
{
//foo后,为什么functor()还能正确执行
//如果functor中被绑定的是一个copy的Foo对象,但是没有调用copy函数
{
Foo foo;
functor = std::bind(&Foo::methodA, &foo);
}
functor();

{
Foo foo;
functor = std::bind(&Foo::methodB, &foo, 100);
}
functor();

{
Foo foo;
functor = std::bind(&Foo::methodC, &foo, string("Foo"));
}
functor();
return 0;
}

...全文
223 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdghchj 2019-03-20
  • 打赏
  • 举报
回复
栈上的对象虽然已经销毁,但原指针所指的内存块数据可能依然存在,这是不安全的代码,运行正常不等于正确。

64,682

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧