您可以在具有相同表示形式的类型之间进行reinterpret_cast吗? [英] Can you reinterpret_cast between types which have the same representation?
问题描述
假设我们有两种类型,它们具有相同的表示形式(相同的成员变量和基类,并且顺序相同).在它们之间进行 reinterpret_cast
是否有效(即不是UB)?例如.从 Mary
到 Ashley&
的 reinterpret_cast
是否有效?那两种类型是多态的怎么办?
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;
}
如果我们知道对象类型以目标类型的成员变量开头,那么如果将对象的开头转换为另一种类型怎么办?例如.这是有效的(即不是UB)吗?
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;
}
请注意,所有主要的编译器都将其视为有效的强制转换(实时演示).问题是,C ++语言是否允许这样做.
Note that all major compilers treat these as a valid casts (live demo). The question is, whether the C++ language allows this.