c++ - Binding member function to a member variable -
c++ - Binding member function to a member variable -
precondition:
here function:
typedef std::function<void (int)> handler; void g(const handler& h) { h(100); }
, , class(original version):
class { 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 print 2 lines, '101' , '102':
int main() { a1(1); a1.f(); a2(2); a2.f(); homecoming 0; }
now realized a::f()
called frequently, modified this(new version):
class { 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 safe bind this
pointer fellow member variable?
is there no functional difference between 2 versions?
can expect new version gain performance benefit? (i suspect compiler(msvc) optimize itself, may not need optimize myself).
ps.: question corrects , replaces previous one: binding fellow member function local static variable
as igor tandetnik mentioned in comments:
is safe bind pointer fellow member variable?
beware compiler-generated re-create constructor , assignment operator. consider:
a a(42); b = a;
here, b.handler
still refers &a
, not &b
. may or may not want.
i don't think performance benefit deserves dev-time effort maintain fellow member variables. (*)
c++ bind
Comments
Post a Comment