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 @ 2021-11-08 21:53  Asp1rant  阅读(393)  评论(0编辑  收藏  举报