什么是"部分重叠的对象"?

Ton*_*ion 12 c++ object undefined-behavior

我刚刚在这个帖子中经历了所有可能的Undefined Behaviors ,其中一个就是

分配给部分重叠的对象的结果

我想知道是否有人能给我一个"部分重叠的对象"的定义,以及代码中如何创建它的例子?

CB *_*ley 5

正如其他答案中所指出的,联合是最明显的安排方式。

这是一个更清晰的例子,说明了使用内置赋值运算符可能会出现部分重叠的对象。如果没有部分重叠的对象限制,此示例不会以其他方式显示 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
}
Run Code Online (Sandbox Code Playgroud)

即使是相同类型的对象,您也可以获得潜在的部分重叠。在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.
}
Run Code Online (Sandbox Code Playgroud)


osg*_*sgx 0

也许他的意思是严格的别名规则?内存中的对象不应与其他类型的对象重叠。

“严格别名是 C(或 C++)编译器做出的一种假设,即解除引用不同类型对象的指针永远不会引用相同的内存位置(即彼此别名。)”