C++11中的数据对齐

C++11中新增了alignof和alignas两个关键字用于数据对齐。alignof可以用于获取类型的对齐字节长度,alignas可以用于改变类型的默认对齐字节长度。

 

Before C++11

在c++11之前,可以通过下面的宏实现对齐。

1 template<class T> struct alignof_trick {char c; T member; };
2 #define ALIGNOF(type) offsetof(alignof_trick<type>, member);

在MSVC中,可以用__alignof获取对齐长度,GCC中则可以通过__alignof__,二者在C++11中得到了统一

 

alignof

alignof用于获得类型的对齐字节长度。

注意事项:

  • alignof在gcc中可用于变量,通常作用于类型
  • 可以和decltype结合使用,但是这种做法只有在类型使用默认对齐才是有效的
  • c++11定义了std::max_align_t,其对齐字节长度要求至少和每个标量类型一样严格,所有的标量类型都适应std::max_align_t的字节对齐长度。

 

alignas

强制数据对齐到某个数,需要注意的是,只能对齐2的幂: 1、2、4、8、16、32、64、128...

 

示例:

复制代码
 1 struct s3
 2 {
 3     char s;
 4     double d;
 5     int i;
 6 };
 7  
 8  
 9 struct s11
10 {
11     alignas(16) char s;
12     int i;
13 };
14  
15 struct s12
16 {
17     alignas(16) char s;
18     int i;
19 };
20  
21  
22 // alignof
23 cout << "-------------------alignof---------------------" << endl;
24 // 基本对齐值
25 cout << "alignof(std::max_align_t)    " << alignof(std::max_align_t) << endl;
26 cout << endl;
27 cout << "-------basic type" << endl;
28 cout << "alignof(char)        " << alignof(char) << endl;
29 cout << "alignof(int)        " << alignof(int) << endl;
30 cout << "alignof(double)    " << alignof(double) << endl;
31  
32 cout << endl;
33 cout << "-------struct" << endl;
34 cout << "alignof(s1)        " << alignof(s1) << endl;
35 cout << "alignof(s2)        " << alignof(s2) << endl;
36 cout << "alignof(s3)        " << alignof(s3) << endl;
37  
38 cout << endl;
39 cout << endl;
40  
41 // alignas
42 cout << "-------------------alignas---------------------" << endl;
43 cout << "alignof(s1)        " << alignof(s1) << endl;
44 cout << "alignof(s11)        " << alignof(s11) << endl;
45 cout << "alignof(s12)        " << alignof(s12) << endl;
46  
47 cout << "sizeof(s1)        " << sizeof(s1) << endl;
48 cout << "sizeof(s11)    " << sizeof(s11) << endl;
49 cout << "sizeof(s12)    " << sizeof(s12) << endl;
复制代码

 

posted @   Asp1rant  阅读(423)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示