gpt4 book ai didi

c++ - 警告 C4121 行为和结构对齐 (Visual Studio 2010)

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:10 25 4
gpt4 key购买 nike

让我们考虑下面的声明。(Visual Studio 2010,警告级别 4)

#pragma pack(push, 2)
#define PADDING 1 // --- <case 1>
/*
#define PADDING 2 // --- <case 2>
*/
struct foo
{
char a[PADDING];
int b;
};

症状

如果您将 PADDING 设置为 <case 1> ,它肯定会产生C4121。但是对于 <case 2> , 它可以在没有任何警告的情况下编译。两种情况的结构布局相同,“b”的偏移量为2个字节。
我希望 C4121 用于 <case 2> ,因为“b”没有对齐 sizeof(int) 的倍数边界。 (来自 MSDN 。我找不到 2010 版本。)

问题

我想知道只有<case 1>是否合理生产 C4121,因为最终的结构布局(对齐)是相同的。
我错过了什么重要的东西吗?我应该忽略 C4121 吗?

附言

其实我也遇到过这种情况

  • default alignment value (8 bytes)
  • pointer to member function of undefined (forward declaration only) class (16 bytes).

所以,我认为具体的对齐值不是重点。我在上面编写了示例代码以使事情变得简单。

最佳答案

如果您忽略此警告,您必须牢记:

When data is not aligned on boundaries that are multiples of the data's size performance can degrade and if you port your code to a RISC machine it will not compile.

至少,您必须决定是否可以冒险抛出异常...

使用 #pragma pack() 来解决这个问题是个好方法,但有一个问题:

The #pragma pack directive can only be used to reduce the packing size of a structure from the project default packing. This leads to interoperability problems with library headers which use for example #pragma pack(8) if you set a project packing to smaller than this. The MSDN documentation[5] states that if the #pragma pack packing is larger than or equal to the project packing, it will be ignored.

For this reason, one should never set a project packing to any value other than the default of 8 bytes, as it would break the #pragma pack directives used in library headers and result in binary incompatibilities between structures.

还有:

the x86 architecture originally did not require aligned memory access and still works without it.

我会建议你避免这个警告,这样会更安全......

解决此问题的方法是按照此处的建议反转 struct 成员的顺序:http://msdn.microsoft.com/en-us/library/kabt0ka3%28v=vs.80%29.aspx

编辑:另一个解释什么是数据结构对齐 以及随之而来的问题的附加链接:https://en.wikipedia.org/wiki/Data_structure_alignment (我建议你阅读定义问题部分)

关于c++ - 警告 C4121 行为和结构对齐 (Visual Studio 2010),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17695933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com