简体   繁体   English

将成员函数绑定到成员变量

[英]Binding member function to a member variable

Precondition: 前提:

Here is a function: 这是一个函数:

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;
};

And this will print two lines, '101' and '102': 这将打印两行“ 101”和“ 102”:

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

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

  return 0;
}

Now I realized A::f() will be called very frequently, 现在我意识到A::f()会被频繁调用,
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;
};

My Questions: 我的问题:

Is it safe to bind this pointer to a member variable? this指针绑定到成员变量是否安全?

Is there no functional difference between two versions? 两个版本之间没有功能上的区别吗?

Can I expect the new version will really gain some performance benefit? 我可以期望新版本确实会获得一些性能优势吗?
(I suspect my compiler(MSVC) will optimize it by itself, (我怀疑我的编译器(MSVC)会自行对其进行优化,
so I may not need to optimize it by myself). 因此我可能不需要自己对其进行优化)。

PS.: This question corrects and replaces the previous one: Binding member function to a local static variable PS .:此问题纠正并替换了前一个问题:将成员函数绑定到局部静态变量

As Igor Tandetnik mentioned in comments: 正如Igor Tandetnik在评论中提到的:

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; 

Here, b.handler still refers to &a , not &b . 在这里, b.handler仍然引用&a ,而不是&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. 我也认为性能优势不值得开发人员花费时间来维护成员变量。 (*) (*)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM