方法: interior_ptr キーワードを含む値型を宣言する (C++/CLI)
interior_ptr は値型で使用することもできます。
重要 |
---|
この言語機能は /clr のコンパイラ オプションには、 /ZW のコンパイラ オプションによってサポートされます。 |
例
Description
C++/CLI の次のサンプルは値型で interior_ptr を使用する方法を示します。
コード
// interior_ptr_value_types.cpp
// compile with: /clr
value struct V {
V(int i) : data(i){}
int data;
};
int main() {
V v(1);
System::Console::WriteLine(v.data);
// pointing to a value type
interior_ptr<V> pv = &v;
pv->data = 2;
System::Console::WriteLine(v.data);
System::Console::WriteLine(pv->data);
// pointing into a value type
interior_ptr<int> pi = &v.data;
*pi = 3;
System::Console::WriteLine(*pi);
System::Console::WriteLine(v.data);
System::Console::WriteLine(pv->data);
}
出力
1
2
2
3
3
3
例
Description
値型では、 this のポインターは interior_ptr に評価されます。
値型 Vの非静的メンバー関数の本体で、 this は値が関数が呼び出されるオブジェクトのアドレスの型 interior_ptr<V> の式です。
コード
// interior_ptr_value_types_this.cpp
// compile with: /clr /LD
value struct V {
int data;
void f() {
interior_ptr<V> pv1 = this;
// V* pv2 = this; error
}
};
例
Description
次のサンプルは静的メンバーを持つアドレス演算子を使用する方法を示します。
静的な Visual C++ 型メンバーのアドレスをネイティブ ポインターについて説明します。静的な値型のメンバーのアドレスは値型のメンバーがランタイム ヒープに割り当てられ、ガベージ コレクターによって移動できるため、マネージ ポインターです。
コード
// interior_ptr_value_static.cpp
// compile with: /clr
using namespace System;
value struct V { int i; };
ref struct G {
static V v = {22};
static int i = 23;
static String^ pS = "hello";
};
int main() {
interior_ptr<int> p1 = &G::v.i;
Console::WriteLine(*p1);
interior_ptr<int> p2 = &G::i;
Console::WriteLine(*p2);
interior_ptr<String^> p3 = &G::pS;
Console::WriteLine(*p3);
}
出力
22
23
hello