将成员函数绑定到局部静态变量 [英] Binding member function to a local static variable

查看:85
本文介绍了将成员函数绑定到局部静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前提条件:

这是一个功能:

typedef std::function<void (int)> Handler;
void g(const Handler& h) {
  h(100);
}

和一个类:

class A {
 public:
  void f0(int n) {
    std::cout << m + n << std::endl;
  }

  void f1() {
    ::g(std::bind(&A::f0, this, std::placeholders::_1));
  }

  int m;
};

这将打印两行,"101"和"102":

And this will print two lines, '101' and '102':

int main() {
  A a1;
  a1.m = 1;
  a1.f1();

  A a2;
  a2.m = 2;
  a2.f1();

  return 0;
}

现在我意识到A::f1()将被非常频繁地调用,
所以我就这样修改了它(新版本):

Now I realized A::f1() will be called very frequently,
so I modified it like this(new version):

  void A::f1() {
    static const Handler kHandler =
        std::bind(&A::f0, this, std::placeholders::_1);

    ::g(kHandler);
  }

我的问题:

this指针绑定到局部静态变量是否安全?

Is it safe to bind this pointer to a local static variable?

两个版本之间在功能上没有区别吗?

Is there no functional difference between two versions?

我可以期望新版本确实会获得一些性能上的好处吗?
(我怀疑我的编译器(MSVC)会自行对其进行优化,
因此我可能不需要自己对其进行优化).

Can I expect the new version will really gain some performance benefit?
(I suspect my compiler(MSVC) will optimize it by itself,
so I may not need to optimize it by myself).

已编辑----------

我运行新版本,并意识到结果与原始版本不同.
它再次打印两行"101"和"101"(而不是"102").
可怜的问题,对不起.

I run the new version and realized that the result is not the same as the original one.
It prints two lines, '101' and '101' again(not '102').
Poor question, sorry for all.

编辑2 ----------

请参考我可能真正打算的新问题:
将成员函数绑定到成员变量

Please refer to my new question which I might truly intend:
Binding member function to a member variable

推荐答案

Raymond Chen的评论是正确的-通过使用静态,您仅创建了一个kHandler实例,并且如果与该首次调用关联的A实例去世了,则绑定的"this"指针将失效.

Raymond Chen's comment is Correct - by using static you're only ever creating one instance of kHandler, and if the instance of A associated with that first call ever dies, then the bound "this" pointer will be dead.

我建议删除静态内容:

void A::f1() {
   const Handler kHandler =
       std::bind(&A::f0, this, std::placeholders::_1);

   ::g(kHandler);
 }

这很安全,因为在g调用的整个生命周期中都存在kHandler.

This is safe because kHandler will exist across the lifetime of the g call.

这篇关于将成员函数绑定到局部静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆