intのsizeが4バイトの環境では、intのデータを4の倍数のアドレスに配置すると、より高速にアクセスできる場合がある。
alignofの返すアライメント要求は、その型のオブジェクトをアドレス上に配置するためのものである。alignofが4の場合、該当のオブジェクトは4の倍数のアドレスに配置する必要がある。
アラインメントを指定するには、alignasを使う。変数及びメンバ変数のアラインメント属性を指定する。alignas(型名) は alignas(alignof(型名)) と同じである。
複数のアラインメントを指定すると、最も大きなアラインメントが選択される。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// alignment.cpp | |
// CplusplusPractice | |
// | |
// Created by masai on 2015/05/21. | |
// Copyright (c) 2015年 masai. All rights reserved. | |
// | |
#include <iostream> | |
using namespace std; | |
// 構造体のすべてのメンバを4バイト単位で配置する例 | |
struct S{ | |
alignas(uint32_t) uint8_t a_; | |
alignas(uint32_t) uint16_t b_; | |
alignas(uint32_t) uint32_t c_; | |
}; | |
int main(){ | |
// int型のアライメント要求 | |
cout << alignof(int) << endl; | |
cout << alignof(uint32_t) << endl; | |
} | |
0 件のコメント:
コメントを投稿