this ポインタ
目次 |
[編集] 構文
this
|
|||||||||
式 this は、prvalue の 式 であり、その値は、暗黙のオブジェクトパラメータ (暗黙のオブジェクトメンバ関数が呼び出されているオブジェクト) のアドレスです。以下のコンテキストで使用できます。
|
3) デフォルトメンバ初期化子内。
4) ラムダ式の キャプチャリスト内。
|
(C++11以降) |
[編集] 説明
this は、その出現の最も内側の囲むクラスにのみ関連付けることができます。たとえその出現がコンテキストで無効であっても。
class Outer { int a[sizeof(*this)]; // Error: not inside a member function unsigned int sz = sizeof(*this); // OK: in default member initializer void f() { int b[sizeof(*this)]; // OK struct Inner { int c[sizeof(*this)]; // Error: not inside a member function of Inner // “this” is not associated with Outer // even if it is inside a member function of Outer }; } };
クラス X のメンバ関数における this の型は X* (X へのポインタ) です。メンバ関数が cv の cv 修飾子シーケンスで宣言されている 場合、this の型は cv X* (同様に cv 修飾された X へのポインタ) です。コンストラクタとデストラクタは cv 修飾子で宣言できないため、それらにおける this の型は、const オブジェクトの構築または破棄時であっても、常に X* です。
クラステンプレートでは、this は 依存式であり、明示的な this-> を使用して、他の式を依存式にするように強制することができます。
template<typename T> struct B { int var; }; template<typename T> struct D : B<T> { D() { // var = 1; // Error: “var” was not declared in this scope this->var = 1; // OK } };
オブジェクトの構築中、オブジェクトまたはそのサブオブジェクトの値が、コンストラクタの this ポインタから直接または間接的に取得されたものではない glvalue を介してアクセスされた場合、そのように取得されたオブジェクトまたはサブオブジェクトの値は未定義です。言い換えれば、コンストラクタでは this ポインタをエイリアスすることはできません。
extern struct D d; struct D { D(int a) : a(a), b(d.a) {} // b(a) or b(this->a) would be correct int a, b; }; D d = D(1); // because b(d.a) did not obtain a through this, d.b is now unspecified
delete this; を実行することは可能ですが、その場合、プログラムはオブジェクトが new によって割り当てられたことを保証する必要があります。しかし、これは、解放されたオブジェクトへのすべてのポインタ、this ポインタ自体を含む無効にします。delete this; が返された後、そのようなメンバ関数はクラスのメンバを参照できません (this は this の暗黙の逆参照を伴うため)し、他のメンバ関数を呼び出すこともできません。
これは、管理対象オブジェクトへの最後の参照がスコープ外に出るときに、参照カウントをデクリメントする責任がある参照カウントポインタのメンバ関数 (例: std::shared_ptr)(C++11 以降) で使用できます。
class ref { // ... void incRef() { ++mnRef; } void decRef() { if (--mnRef == 0) delete this; } };
[編集] キーワード
[編集] 例
class T { int x; void foo() { x = 6; // same as this->x = 6; this->x = 5; // explicit use of this-> } void foo() const { // x = 7; // Error: *this is constant } void foo(int x) // parameter x shadows the member with the same name { this->x = x; // unqualified x refers to the parameter // “this->” is required for disambiguation } int y; T(int x) : x(x), // uses parameter x to initialize member x y(this->x) // uses member x to initialize member y {} T& operator=(const T& b) { x = b.x; return *this; // many overloaded operators return *this } };
[編集] 欠陥レポート
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| CWG 760 | C++98 | ネストされたクラスで this が使用された場合、それは ネストされたクラスまたは囲むクラスのどちらに関連付けられるか 未指定でした。 |
this は常に 最も内側のネストされたクラス に関連付けられます。 それが非静的メンバ関数内であっても |
| CWG 2271 | C++98 | this はエイリアスされる可能性がありました。 非 const オブジェクトの構築時。 |
この場合も エイリアスは禁止されています。 |
| CWG 2869 | C++98 | 非関連クラスの静的メンバ関数で this が使用できるかどうかは 不明でした。 |
明確化された |