Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตัวดำเนินการ alignof ใน C++


บทนำ

alignof เป็นตัวดำเนินการ (operator) ที่คืนค่า alignment (การจัดวางหน่วยความจำ) ที่จำเป็นสำหรับชนิดข้อมูลที่กำหนด ค่าที่คืนเป็นหน่วยไบต์ (bytes)

Syntax

var align = alignof(type)

ตัวอย่าง: Alignment ของชนิดข้อมูลพื้นฐาน

#include <iostream>
using namespace std;

int main() {
    cout << "Alignment of char: " << alignof(char) << endl;
    cout << "Alignment of int: " << alignof(int) << endl;
    cout << "Alignment of float: " << alignof(float) << endl;
    cout << "Alignment of double: " << alignof(double) << endl;
    cout << "Alignment of pointer: " << alignof(int*) << endl;
    return 0;
}

ผลลัพธ์ (ตัวอย่างบนระบบ 64-bit)

Alignment of char: 1
Alignment of int: 4
Alignment of float: 4
Alignment of double: 8
Alignment of pointer: 8

ตัวอย่าง: Alignment ของ Array และ Struct

#include <iostream>
using namespace std;

struct basic { int i; float f; char s; };
struct Empty { };

int main() {
    cout << "Alignment of char[10]: " << alignof(char[10]) << endl;
    cout << "Alignment of int[10]: " << alignof(int[10]) << endl;
    cout << "Alignment of float[10]: " << alignof(float[10]) << endl;
    cout << "Alignment of class basic: " << alignof(basic) << endl;
    cout << "Alignment of Empty class: " << alignof(Empty) << endl;
    return 0;
}

ผลลัพธ์

Alignment of char[10]: 1
Alignment of int[10]: 4
Alignment of float[10]: 4
Alignment of class basic: 4
Alignment of Empty class: 1

เปรียบเทียบ sizeof() และ alignof()

#include <iostream>
using namespace std;

int main() {
    cout << "alignof(char): " << alignof(char) << ", sizeof(char): " << sizeof(char) << endl;
    cout << "alignof(int*): " << alignof(int*) << ", sizeof(int*): " << sizeof(int*) << endl;
    cout << "alignof(float): " << alignof(float) << ", sizeof(float): " << sizeof(float) << endl;
    return 0;
}

ผลลัพธ์

alignof(char): 1, sizeof(char): 1
alignof(int*): 8, sizeof(int*): 8
alignof(float): 4, sizeof(float): 4