C++中的操作符对齐

在C++11中 对齐 运算符用于返回对齐方式,以指定类型的字节为单位。 语法:

null
alignof(type)

语法解释:

  • 包括: 运算符返回类型实例所需的字节对齐方式,该类型为完整类型、数组类型或引用类型。
  • 数组类型: 返回元素类型的对齐要求。
  • 参考类型: 运算符返回引用类型的对齐方式。

返回值: alignof运算符通常用于返回类型为的值 标准:尺寸 .

节目:

// C++ program to demonstrate alignof operator
#include <iostream>
using namespace std;
struct Geeks {
int i;
float f;
char s;
};
struct Empty {
};
// driver code
int main()
{
cout << "Alignment of char: " << alignof( char ) << endl;
cout << "Alignment of pointer: " << alignof( int *) << endl;
cout << "Alignment of float: " << alignof( float ) << endl;
cout << "Alignment of class Geeks: " << alignof(Geeks) << endl;
cout << "Alignment of Empty class: " << alignof(Empty) << endl;
return 0;
}


输出:

Alignment of char: 1
Alignment of pointer: 8
Alignment of float: 4
Alignment of class Geeks: 4
Alignment of Empty class: 1

校准与尺寸: 这个 对齐 值与基本类型的sizeof值相同。考虑一下这个例子:

typedef struct { int a; double b; } S;  
// alignof(S) == 8  

在上述情况下 对齐 值是结构中最大元素的对齐要求。 演示alignof和sizeof之间差异的示例程序:

// C++ program to demonstrate
// alignof vs sizeof operator
#include <iostream>
using namespace std;
struct Geeks {
int i;
float f;
char s;
};
int main()
{
cout << "alignment of Geeks : " << alignof(Geeks) << '' ;
cout << "sizeof of Geeks : " << sizeof (Geeks) << '' ;
cout << "alignment of int : " << alignof( int ) << '' ;
cout << "sizeof of int     : " << sizeof ( int ) << '' ;
}


输出:

alignment of Geeks : 4
sizeof of Geeks : 12
alignment of int : 4
sizeof of int     : 4

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享