c++ - 什么是 'partially overlapping objects' ?

标签 c++ object undefined-behavior

我刚刚经历了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/

相关文章:

c++ - 我可以使用 Poco 从内存缓冲区创建多文件 zip 存档吗?

c++ - 窗口的 C\C++ LINPACK 源代码免费用于商业用途?

java - 创建新对象时使用字符串作为标识符

javascript - 将类似数组的对象属性转换为数组不起作用

c++ - 了解从多个类派生时的虚函数

c++ - 不评估应用了 sizeof 的表达式是否使得在 C++ 中取消引用 sizeof 内的空指针或无效指针是合法的?

c++ - LNK2019上一个带dll项目的解决方案

java - 为什么这个 java 代码没有在 Eclipse IDE 上显示。公共(public)类型App必须在自己的文件中定义

c++ - 表达式 : deque iterator not incrementable (special case - i can't figure it out)

c++ - 如何减少C++程序的崩溃