Hacker News new | ask | show | jobs
by gpderetta 2308 days ago
there is nothing wrong with them, but pointers to member do not close over this, so you still need some form of binding to use them as callbacks.
1 comments

Well, when you invoke a pointer to member, you need an actual object (a this) to invoke it on. So when the member runs, it has a this.

But it sounds like what you want is a "handle" or some such term, by which you can invoke a member function on an object, and all you need to do so is the handle. That's a different problem than pointers to members are trying to solve, but you can do that quite easily with a function object. That's essentially a roll-your-own closure, and since you can define whatever data members you want, you can close over anything.

One thing you have to watch out for, though, is lifetimes. C++ is not garbage-collected, and so it will not preserve an object just because another object has a pointer or reference to it. If you create a function object that captures a pointer to member, and a "this" to invoke it on, and the "this" gets destroyed, and then you use the function object, you're going to get chaos.