Natural alignment is typically based on the size of the data type. Here's a practical guide to common alignment requirements:
#include <iostream>
int main() {
std::cout << "Alignment requirements:\n"
<< "char: " << alignof(char) << " bytes\n"
<< "short: " << alignof(short) << " bytes\n"
<< "int: " << alignof(int) << " bytes\n"
<< "long: " << alignof(long) << " bytes\n"
<< "float: " << alignof(float) << " bytes\n"
<< "double: " << alignof(double) << " bytes\n"
<< "pointer: " << alignof(int*) << " bytes\n";
}
Alignment requirements:
char: 1 bytes
short: 2 bytes
int: 4 bytes
long: 8 bytes
float: 4 bytes
double: 8 bytes
pointer: 8 bytes
For compound types like structs and classes, the alignment is typically determined by the largest alignment requirement of any member:
#include <iostream>
struct Example {
char A;// 1 byte alignment
double B;// 8 byte alignment
int C;// 4 byte alignment
};
int main() {
std::cout << "Struct alignment: "
<< alignof(Example) << " bytes\n";
}
Struct alignment: 8 bytes
You can use the alignas
specifier to request specific alignment:
#include <iostream>
struct alignas(16) Custom {
int Value;
};
int main() {
std::cout << "Custom alignment: "
<< alignof(Custom) << " bytes\n";
// This will always start at a 16-byte boundary
Custom Instance;
}
Remember:
alignof()
operator tells you alignment requirementsAnswers to questions are automatically generated and may not have been reviewed.
Learn how memory alignment affects data serialization and how to handle it safely