sizeof 演算子
提供: cppreference.com
オブジェクトまたは型のサイズを問い合わせます。
オブジェクトの実際のサイズを知る必要があるときに使用されます。
目次 |
[編集] 構文
sizeof( type )
|
(1) | ||||||||
sizeof expression
|
(2) | ||||||||
どちらのバージョンも std::size_t 型の定数式です。
[編集] 説明
2) 評価された場合の expression の型のオブジェクト表現のバイト単位のサイズを返します。
[編集] ノート
コンピュータアーキテクチャによっては、バイトは8ビットより大きいかもしれません。 正確な値は CHAR_BIT で取得できます。
sizeof(char)、 sizeof(char8_t)、 sizeof(signed char) および sizeof(unsigned char) は常に 1 と等しくなります。
sizeof は関数型、不完全型、またはビットフィールドの glvalue で使用することはできません。
参照型に適用されたときは、結果はその参照先の型のサイズです��
クラス型に適用されたときは、結果はそのオブジェクトのサイズに配列内でそのようなオブジェクトを配置するために要求される追加のパディングを加えたものになります。
sizeof
は必ず非ゼロの値を返します (たとえ空のクラス型に適用された場合でも)。
式に適用されたときは、 sizeof
はその式を評価しません。 たとえその式が多相オブジェクトを指す場合でも、結果はその式の静的な型のサイズです。 左辺値から右辺値、配列からポインタ、関数からポインタへの変換は行われません。 しかし、 prvalue の引数に対する一時具体化は (形式的には) 行われます。 sizeof はその結果のオブジェクトのサイズを調べます。 (C++17以上)
[編集] キーワード
[編集] 例
出力例はポインタが64ビットでintが32ビットのシステムのものです。
Run this code
#include <iostream> struct Empty {}; struct Base { int a; }; struct Derived : Base { int b; }; struct Bit { unsigned bit: 1; }; int main() { Empty e; Derived d; Base& b = d; [[maybe_unused]] Bit bit; int a[10]; std::cout << "size of empty class: " << sizeof e << "\n" << "size of pointer: " << sizeof &e << "\n" // << "size of function: " << sizeof(void()) << "\n" // エラー // << "size of incomplete type: " << sizeof(int[]) << "\n" // エラー // << "size of bit field: " << sizeof bit.bit << "\n" // エラー << "size of array of 10 int: " << sizeof(int[10]) << "\n" << "size of array of 10 int (2): " << sizeof a << "\n" << "length of array of 10 int: " << ((sizeof a) / (sizeof *a)) << "\n" << "length of array of 10 int (2): " << ((sizeof a) / (sizeof a[0])) << "\n" << "size of the Derived: " << sizeof d << "\n" << "size of the Derived through Base: " << sizeof b << "\n"; }
出力例:
size of empty class: 1 size of pointer: 8 size of array of 10 int: 40 size of array of 10 int (2): 40 length of array of 10 int: 10 length of array of 10 int (2): 10 size of the Derived: 8 size of the Derived through Base: 4
[編集] 関連項目
sizeof の C言語リファレンス
|