Hacker News new | ask | show | jobs
by AnimalMuppet 2311 days ago
What's so awful about pointer to member? I've used it a couple of times, and didn't think it was particularly weird. I mean, yes, I had to look up the syntax, but it was rather straightforward.
1 comments

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.
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.