- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
直到今天,我使用以下技术来打包结构:
#pragma pack(push,1)
struct mystruct
{
char a1;
char a2;
int a3;
}
#pragma pack(pop)
mystruct mydata()
{
mystruct ms;
ms.a1='a';
ms.a2='b';
ms.a3=12;
return ms;
}
并假设ms打包为1,但今天有人告诉我,在上面的定义中,ms被打包为4,因为pack对定义没有影响,但对声明有影响。 http://msdn.microsoft.com/en-us/library/aa273913%28v=vs.60%29.aspx
谁能澄清我做的是否正确?
最佳答案
标准规定了§3.1/2
A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a functionbody, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attributedeclaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).
因此你有一个你正确指出的结构定义,但它也是一个声明
pack has no effect on definitions
适用,但不适用于声明。事实上,MSVC 和 gcc/clang 正确地用 1 打包了上面的内容
struct mystruct_not_packed
{
char a1;
char a2;
int a3;
};
#pragma pack(push,1)
struct mystruct
{
char a1;
char a2;
int a3;
};
mystruct_not_packed object; // This doesn't apply
#pragma pack(pop)
int main(int argc, char *argv[])
{
std::cout << sizeof(mystruct) << std::endl; // 6
std::cout << sizeof(mystruct_not_packed) << std::endl; // 8
std::cout << sizeof(object) << std::endl; // 8
}
(使用 MSVC2013U4 测试)
关于c++ - 如何在 vs 和 gcc 中使用 pack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26462279/
我是一名优秀的程序员,十分优秀!