I put the tag language lawyer
, although I have the feeling that this is on the wrong side of the standard boundary. I haven't seen a conversation exactly on this point, and but I had at work, so I would like to have some certainty about this.
The issue is accessing (potentially) private fields of virtual base classes. Say I compute the offset of a private field of a class, and then use this offset outside the class to access (read/write) the member variable at this location.
I saw that there is an extension for GCC and clang offsetof
(this one is conditionally defined in C++17, what does it mean?), and using it is equivalent to some pointer arithmetic like this:
#include <iostream>
class A
{
int a{};
public:
int aa{};
static ptrdiff_t getAOffset()
{
A instance;
return reinterpret_cast<ptrdiff_t>(static_cast<const void*>(&instance)) - reinterpret_cast<ptrdiff_t>(static_cast<const void*>(&(instance.a)));
//return offsetof(A, a); // "same" as this call to offset
}
int get() const
{
return a;
}
};
class B: public virtual A
{
};
void update_field(char* pointer, ptrdiff_t offset, int value)
{
int* field = reinterpret_cast<int*>(pointer + offset);
*field = value;
}
void modify_a(B& instance)
{
update_field(reinterpret_cast<char*>(dynamic_cast<A*>(&instance)), A::getAOffset(), 1);
}
int main()
{
B instance;
std::cout << instance.get() << std::endl;
modify_a(instance);
std::cout << instance.get() << std::endl;
}
I also made a coliru (pedantic) that doesn't complain, but still... https://coliru.stacked-crooked.com/a/faecd0b248eff651
Is there something in the standard that authorizes this or is this in undefined behavior land? Happy to see also if there is a difference between the standards.