我刚刚经历了this 中所有可能的未定义行为。线程,其中之一是
The result of assigning to partially overlapping objects
我想知道是否有人可以给我一个“部分重叠对象”的定义以及如何创建它的代码示例?
最佳答案
正如其他答案中指出的那样, union 是最明显的安排方式。
这是一个更清晰的示例,说明内置赋值运算符可能如何产生部分重叠的对象。如果不是部分重叠的对象限制,此示例将不会显示 UB。
union Y {
int n;
short s;
};
void test() {
Y y;
y.s = 3; // s is the active member of the union
y.n = y.s; // Although it is valid to read .s and then write to .x
// changing the active member of the union, .n and .s are
// not of the same type and partially overlap
}
即使是相同类型的对象,您也可能会出现部分重叠。在 short
严格大于 char
的情况下考虑这个示例,该实现不向 X
添加填充。
struct X {
char c;
short n;
};
union Y {
X x;
short s;
};
void test() {
Y y;
y.s = 3; // s is the active member of the union
y.x.n = y.s; // Although it is valid to read .s and then write to .x
// changing the active member of the union, it may be
// that .s and .x.n partially overlap, hence UB.
}
关于c++ - 什么是 'partially overlapping objects' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7292862/