4 ms·
Ok, lovely, but why is this useful? Like, is there any problem where this is the simplest way to solve it?
by marvy 9y ago
Ok, 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.)