The Wayback Machine - https://web.archive.org/web/20180407202812/http://ja.cppreference.com:80/w/cpp/language/constant_initialization
名前空間
変種
操作

constant initialization

提供: cppreference.com
< cpp‎ | language

 
 
C++言語
一般的なトピック
フロー制御
条件付き実行文
繰り返し文 (ループ)
ジャンプ文
関数
関数宣言
ラムダ関数宣言
inline 指定子
例外指定(廃止予定)
noexcept 指定子(C++11)
例外
名前空間
指定子
decltype(C++11)
auto(C++11)
alignas(C++11)
記憶域期間指定子
初期化
代替表現
リテラル
ブーリアン - 整数 - 浮動小数点
文字 - 文字列 - nullptr(C++11)
ユーザ定義(C++11)
ユーティリティ
アトリビュート(C++11)
typedef 宣言
型エイリアス宣言(C++11)
キャスト
暗黙の変換 - 明示的な変換
static_cast - dynamic_cast
const_cast - reinterpret_cast
メモリ確保
クラス
クラス固有の関数特性
特別なメンバ関数
テンプレート
その他
 

Sets the initial values of the static constants

目次

[編集]構文

staticT&ref= constexpr; (1)
staticTobject= constexpr; (2)

[編集]説明

Constant initialization is performed after zero initialization of the static and thread-local objects and before all other initialization. Only the following variables are constant initialized:

1) Static or thread-local references, if it is bound to static lvalue or to a temporary. and if every expression (including implicit conversions) in the initializer of the reference is a 定数式.
2) Static or thread-local object of class type that is initialized by a constructor call, if the constructor is constexpr and all constructor arguments (including implicit conversions) are constant expressions, and if the initializers in the constructor's initializer list and the brace-or-equal initializers of the class memebers only contain constant expressions.
3) Static or thread-local object (not necessarily of class type), that is not initialized by a constructor call, if every expression in its initializer is a constant expression.

The effects of constant initialization are the same as the effects of the corresponding initialization, except that it's guaranteed that it is complete before any other initialization of a static or thread-local object begins, and it may be performed at compile time.

The object that was initialized by constant initialization can be used in constant expressions, e.g. in an array declaration.

[編集]ノート

The compiler is permitted to initialize other static and thread-local objects using constant initialization, if it can guarantee that the value would be the same as if the standard order of initialization was followed. Such objects can be used in constant expressions, but this use is not portable.

[編集]

#include <iostream>#include <array>   struct S {staticconstint c;};constint d =10* S::c;// not a constant expression: S::c has no preceding// initializer, this initialization happens after constconstint S::c=5;// constant initialization, guaranteed to happen firstint main(){std::cout<<"d = "<< d <<'\n';std::array<int, S::c> a1;// OK: S::c is a constant expression// std::array<int, d> a2; // error: d is not a constant expression}

出力:

d = 50

[編集]参照

close