2015年5月21日木曜日

alignment(C++11)

アラインメントとは、オブジェクトのための領域をメモリ上に確保する際のアドレスの境界位置のこと。
intのsizeが4バイトの環境では、intのデータを4の倍数のアドレスに配置すると、より高速にアクセスできる場合がある。

alignofの返すアライメント要求は、その型のオブジェクトをアドレス上に配置するためのものである。alignofが4の場合、該当のオブジェクトは4の倍数のアドレスに配置する必要がある。

アラインメントを指定するには、alignasを使う。変数及びメンバ変数のアラインメント属性を指定する。alignas(型名) は alignas(alignof(型名)) と同じである。

複数のアラインメントを指定すると、最も大きなアラインメントが選択される。

//
// 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;
}
view raw alignment.cpp hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿