3 ms·
Can someone remind me what that's for? I never use it, I keep trying to look it up and then I forget it again. Maybe because I never quite understood it prope
by marvy 10y ago
Can someone remind me what that's for? I never use it, I keep trying to look it up and then I forget it again. Maybe because I never quite understood it properly.
- smitherfield 9y agoI'm batting 0 for 2 so far in this thread, but I'll take a stab at it now I've been reminded of those crazy beasts' existence. :) struct Foo { int i; int inc() { return ++i; } }; int Foo::*i_ptr = &Foo::i; // Pointer to member int (Foo::*inc_ptr)() = &Foo::inc; // Pointer to method Foo my_foo(0); (&my_foo)->i_ptr; // Error: my_foo has no member "i_ptr" (&my_foo)->*i_ptr; // OK my_foo.inc_ptr(); // Error: my_foo has no member "inc_ptr" my_foo.*inc_ptr(); // OK // This is also why you can't create references // to methods or other class members int (&print)(const char *) = std::puts; // OK int (Foo::&inc_ref)() = Foo::inc; // Error int &my_int = my_foo.i; // OK int Foo::&i_ref = Foo::i; // Error
- marvy 9y agoOk, lovely, but why is this useful? Like, is there any problem where this is the simplest way to solve it?
- a_t48 9y agoIt's basically a way to use the result of a pointer to a member. Let's say you have class Foo { int m_bar; int m_baz; } You want to store off which member of Foo you want to reference, but you want to do it in a way not tied to any specific instance of Foo. int (Foo :: * ptr) = &Foo::m_baz; // Basically offsetof() but safely typed. Cool, but now what are you going to do with that member? What if I want to set it to 10? int (Foo :: * ptr) = &Foo::m_baz; std::vector<Foo*> foos; ... // populate foos; for(Foo* foo : foos) { // For each foo, set whatever member ptr points at to 10 foo->*ptr = 10; } I've never seen it really used in practice (usually I see offsetof() and pointer math in this situation because the object type isn't known before hand) but it's an option.
- marvy 9y agoSo you have seen offsetof used in practice? Can I have a pointer? (I will not confirm or deny whether that pun was intentional.)