将成员函数绑定到成员变量 [英] Binding member function to a member variable

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

问题描述

前提条件:

这是一个功能:

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

和一个类(原始版本):

, and a class(original version):

class A {
 public:
  A(int arg)
    : m(arg) {}

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

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

 private:
  const int m;
};

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

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

int main() {
  A a1(1);
  a1.f();

  A a2(2);
  a2.f();

  return 0;
}

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

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

class A {
 public:
  A(int arg)
    : m(arg),
      handler(std::bind(&A::f0, this, std::placeholders::_1)) {}

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

  void f() {
    ::g(handler);
  }

 private:
  const int m;
  const Handler handler;
};

我的问题:

this指针绑定到成员变量是否安全?

Is it safe to bind this pointer to a member 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).

PS .:此问题更正并替换了先前的问题: 将成员函数绑定到局部静态变量

PS.: This question corrects and replaces the previous one: Binding member function to a local static variable

推荐答案

正如Igor Tandetnik在评论中所述:

As Igor Tandetnik mentioned in comments:

将此指针绑定到成员变量是否安全?

Is it safe to bind this pointer to a member variable?

当心编译器生成的副本构造函数和赋值运算符.考虑:

Beware the compiler-generated copy constructor and assignment operator. Consider:

A a(42); A b = a;

在这里,b.handler仍然引用&a,而不是&b.这可能是您想要的,也可能不是.

Here, b.handler still refers to &a, not &b. This may or may not be what you want.

我也不认为性能收益值得开发人员花费时间来维护成员变量. (*)

I also don't think the performance benefit deserves dev-time effort to maintain member variables. (*)

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

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