yohhoyの日記

技術的メモをしていきたい日記

参照型変数とメモリの関係

プログラミング言語C++の言語仕様では、メモリ空間上に 参照型(reference type) の実体が存在するか否かを規定しない(unspecified)。

  • スカラ型(scalar type)=算術型/列挙型/ポインタ型やその配列型などのオブジェクト(object)は、メモリ空間上に実体が配置される=メモリ空間の一定領域を占有する。*1
  • 参照型(reference type)変数はオブジェクトに付ける「別名ラベル」であり、言語仕様としてはメモリ空間上の実体を要求しない。このため、sizeof演算子&単項演算子は “参照型変数それ自身” に対してではなく、“参照先のオブジェクト” に対して適用される。
  • 現実のC++言語処理系(=コンパイラ)では、参照型変数はポインタ値を用いて実現するケースが多い。仕様と実装の区別に注意。

C++14 1.7/p3, 8.3.2/p4より一部引用(下線部は強調)。

A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having non-zero width. [Note: Various features of the language, such as references and virtual functions, might involve additional memory locations that are not accessible to programs but are managed by the implementation. -- end note] (snip)

It is unspecified whether or not a reference requires storage.

Linux

Linuxおよびその互換システムが採用するC++ ABI(Application Binary Interface)では、参照型パラメータはポインタ値渡しとして実装される。Itanium C++ ABI仕様より該当箇所を引用。

3.1.2 Reference Parameters
Reference parameters are handled by passing a pointer to the actual parameter.

Itanium C++ ABI(Revision 1.86)

Windows/MSVC

Microsoft Visual C++(MSVC)コンパイラが生成するアセンブリコードをみる限り、参照型はポインタとして実装される様子。公開ABI仕様はおそらく存在しない。

関連URL:

*1:C++言語仕様としては、全てのスカラ型オブジェクトに対してメモリ位置(memory location)が割り当てられる。一方、言語仕様が定める “as-ifルール” に基づいた最適化処理によって、スカラ型であってもメモリ空間上に実体が存在しないケースも生じる。