3 ms·
It'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 w
by a_t48 10y ago
It'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 10y agoSo you have seen offsetof used in practice? Can I have a pointer? (I will not confirm or deny whether that pun was intentional.)