Suppose we have two types, that have the same representation (the same member variables and base classes, in the same order). Is it valid (i.e. not UB) to reinterpret_cast
between them? E.g. is it valid to reinterpret_cast
from Mary
to Ashley&
? And what if the two types are polymorphic?
struct Mary {
int m1;
char m2;
};
struct Ashley {
int a1;
char a2;
};
int TryTwins ()
{
Mary mary = {};
Ashley& ashley = reinterpret_cast<Ashley&> (mary);
ashley.a1 = 1;
ashley.a2 = 2;
return mary.m1 + mary.m2;
}
What if we cast the beginning of an object to another type, if we know that the source type starts with the member variables of the target type? E.g. is this valid (i.e. not UB)?
struct Locomotive {
int engine;
char pantograph;
};
struct Train {
int engine;
char pantograph;
int* wagon1;
int** wagon2;
int*** wagon3;
};
int TryTrain ()
{
Train train = {};
Locomotive& loc = reinterpret_cast<Locomotive&> (train);
loc.engine = 1;
loc.pantograph = 2;
return train.engine + train.pantograph;
}
Note that all major compilers treat these as a valid casts (live demo). The question is, whether the C++ language allows this.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…