C ++中的#pragma pack [英] #pragma pack in C++

查看:74
本文介绍了C ++中的#pragma pack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C ++中,对于typedef结构,我们需要具有#pragma pack?特别是在网络通信中使用这些结构时.

why do we need to have #pragma pack for typedef structure in C++? Specifically when you are using those structure in network communication.

推荐答案

#pragma pack控制结构成员的对齐方式.通用默认设置为8,以确保最多8个字节长的成员在其大小倍数的地址上对齐.例如,双精度或64位指针.读取或写入未对齐的双精度数据可能会非常昂贵,如果跨越CPU缓存行边界,通常会慢三倍.这种对齐方式会在成员之间产生未使用的空间,称为填充.

#pragma pack controls the alignment of members of a structure. The common default setting is 8, ensuring that members that are up to 8 bytes long get aligned on an address that's a multiple of their size. A double or 64-bit pointer for example. Reading or writing a mis-aligned double can be quite expensive, typically three times slower if it straddles a CPU cache line boundary. This alignment can produce unused space between members, called padding.

这种对齐方式通常不适用于网络框架,它们往往被紧密包装而没有任何填充,#pragma pack(push,1)

This kind of alignment is often inappropriate for network frames, they tend to be tightly packed without any padding, #pragma pack(push, 1)

这篇关于C ++中的#pragma pack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆