C++11中的数据对齐
2021/11/8 22:10:30
本文主要是介绍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;
这篇关于C++11中的数据对齐的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-07fastcgi 是什么-icode9专业技术文章分享
- 2024-10-07fastcgi 的详细使用教程介绍-icode9专业技术文章分享
- 2024-10-07git如何更新单个文件到本地-icode9专业技术文章分享
- 2024-10-07如何使用ASM(Abstract Syntax Tree Manipulation)技术来修改第三方AAR依赖中的函数-icode9专业技术文章分享
- 2024-10-07Activity 跳转时间耗时很长怎么优化解决-icode9专业技术文章分享
- 2024-10-07Androud Toast 有哪些常用的第三方组件-icode9专业技术文章分享
- 2024-10-07在viewmodel中怎么使用 mmkv?-icode9专业技术文章分享
- 2024-10-07MMKV.defaultMMKV() 是单例模式吗?-icode9专业技术文章分享
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享