什么是“部分重叠的对象”?
I was just going through all the possible Undefined Behaviours in this thread, and one of them is
The result of assigning to partially overlapping objects
I wondered if anyone could give me a definition of what "partially overlapping objects" are and an example in code of how that could possibly be created?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如其他答案所指出的,工会是安排这一点的最明显的方式。
这是一个更清晰的示例,说明了内置赋值运算符如何可能出现部分重叠的对象。如果不是部分重叠的对象限制,此示例将不会表现出 UB。
即使对于相同类型的对象,您也可能会出现部分重叠。考虑此示例,在不向
X
添加填充的实现中,short
严格大于char
。As pointed out in other answers, a union is the most obvious way to arrange this.
This is an even clearer example of how partially overlapping objects might arise with the built in assignment operator. This example would not otherwise exhibit UB if it were not for the partially overlapping object restrictions.
You can get potential partial overlap even with objects of the same type. Consider this example in the case where
short
is strictly larger thanchar
on an implementation that adds no padding toX
.联合 就是一个很好的例子。
您可以创建具有重叠成员的内存结构。
例如(来自 MSDN):
现在如果您使用分配 char 成员,则所有其他成员都未定义。这是因为它们位于同一内存块,并且您只为其一部分设置了实际值:
如果您随后尝试访问 blah.i 或 blah.d< /strong> 或 blah.f 它们将具有未定义的值。 (因为只有第一个字节(即字符)设置了其值)
A union is a good example for that.
You can create a structure of memory with overlapping members.
for example (from MSDN):
now if you use assign the char member all other member are undefined. That's because they are at the same memory block, and you've only set an actual value to a part of it:
If you will then try to access blah.i or blah.d or blah.f they will have an undefined value. (because only first byte, which is a char, had its value set)
这是指指针别名的问题,在 C++ 中禁止指针别名,以便编译器更容易优化。可以在此线程中找到对该问题的良好解释
This refers to the problem of pointer aliasing, which is forbidden in C++ to give compilers an easier time optimizing. A good explanation of the problem can be found in this thread
也许他的意思是严格的别名规则?内存中的对象不应与其他类型的对象重叠。
May be he mean a strict aliasing rule? Object in memory should not overlap with object of other type.
典型的示例是使用 memcpy:
memcpy 是未定义行为的原因是因为没有执行复制所需的算法。在这种情况下,引入了
memmove
作为安全的替代方案。The canonical example is using memcpy:
The reason why memcpy is undefined behavior is because there's no required algorithm for performing the copy. In this circumstance,
memmove
was introduced as a safe alternative.