__declspec

Microsoft 固有の仕様

ストレージ クラス情報を指定するための拡張属性構文は、__declspec キーワードを使用します。指定した型のインスタンスは、このキーワードに指定した Microsoft 固有のストレージ クラス属性 (以降の一覧を参照) を付けて保存されます。 ストレージ クラス修飾子の例には、他に static および extern キーワードがあります。 ただし、これらのキーワードは C および C++ 言語の ANSI 仕様の一部であるため、拡張属性構文では扱われません。 拡張属性構文は、Microsoft 固有の C および C++ 言語拡張を簡略化し、標準化します。

構文

decl-specifier:
__declspec ( extended-decl-modifier-seq )

extended-decl-modifier-seq:
extended-decl-modifieropt
extended-decl-modifier extended-decl-modifier-seq

extended-decl-modifier:
align(number)
allocate("segname")
allocator
appdomain
code_seg("segname")
deprecated
dllimport
dllexport
empty_bases
jitintrinsic
naked
noalias
noinline
noreturn
nothrow
novtable
no_sanitize_address
process
property( { get=get-func-name | ,put=put-func-name } )
restrict
safebuffers
selectany
spectre(nomitigation)
thread
uuid("ComObjectGUID")

空白は、宣言修飾子のシーケンスを区切ります。 その例は以降のセクションで示します。

拡張属性文法では、次の Microsoft 固有のストレージ クラス属性がサポートされています: alignallocateallocatorappdomaincode_segdeprecateddllexportdllimportempty_basesjitintrinsicnakednoaliasnoinlinenoreturnnothrownovtableno_sanitize_addressprocessrestrictsafebuffersselectanyspectre、および thread。 また、次の COM オブジェクトの属性もサポートしています: property および uuid

code_segdllexportdllimportempty_basesnakednoaliasnothrowno_sanitize_addresspropertyrestrictselectanythread、および uuid ストレージ クラス属性は、適用先のオブジェクトまたは関数の宣言のみのプロパティです。 thread 属性はデータとオブジェクトにのみ影響を与えます。 naked および spectre 属性は関数のみに影響を与えます。 dllimport および dllexport 属性は関数、データ、オブジェクトに影響を与えます。 propertyselectany、および uuid 属性は COM オブジェクトに影響を与えます。

以前のバージョンとの互換性を確保するために、_declspec は、コンパイラ オプション /Za (言語拡張機能の無効化) が指定されていない限り、__declspec の同意語です。

__declspec キーワードは単純な宣言の先頭に置く必要があります。 コンパイラは、宣言内の変数識別子の前に * または > の後に配置された__declspecキーワード (keyword)を、警告なしで無視します。

ユーザー定義型の宣言の先頭で指定された __declspec 属性は、その型の変数に適用されます。 次に例を示します。

__declspec(dllimport) class X {} varX;

この場合、属性は varX に適用されます。 class または struct キーワードの後に置かれた __declspec 属性はユーザー定義の型に適用されます。 次に例を示します。

class __declspec(dllimport) X {};

この場合、属性は X に適用されます。

単純な宣言に __declspec 属性を使用するための一般的なガイドラインは次のとおりです。

decl-specifier-seq init-declarator-list ;

decl-specifier-seq には、特に基本データ型 (intfloattypedef、またはクラス名など)、ストレージ クラス (staticextern など)、または __declspec 拡張が含まれている必要があります。 init-declarator-list には特に、宣言のポインターの一部を含める必要があります。 次に例を示します。

__declspec(selectany) int * pi1 = 0;   //Recommended, selectany & int both part of decl-specifier
int __declspec(selectany) * pi2 = 0;   //OK, selectany & int both part of decl-specifier
int * __declspec(selectany) pi3 = 0;   //ERROR, selectany is not part of a declarator

次のコードでは、整数型のスレッド ローカル変数を宣言して特定の値に初期化します。

// Example of the __declspec keyword
__declspec( thread ) int tls_i = 1;

Microsoft 固有の仕様はここまで

関連項目

キーワード
C の拡張ストレージ クラス属性