名稱空間
變體
操作

this 指標

來自 cppreference.com
< cpp‎ | 語言
 
 
C++ 語言
 
 

目錄

[編輯] 語法

this

表示式 this 是一個 純右值 表示式,其值是 隱式物件引數(正在呼叫隱式物件成員函式的物件)的地址。它可以在以下上下文中出現:

1) 在任何隱式物件成員函式的函式體中,包括成員初始化列表lambda 表示式體(C++11 起)
2) 在任何隱式物件成員函式的宣告中,在(可選的)cv 限定符序列之後的任何位置,包括異常規範和尾隨返回型別(C++11 起)
4) 在 lambda 表示式的捕獲列表中。
(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 的型別始終是 X*,即使在構造或銷燬 const 物件時也是如此。

在類模板中,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 指標獲取的左值訪問物件或其任何子物件的值,則這樣獲取的物件或子物件的值是未指定的。換句話說,在建構函式中,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

如果程式能保證物件是透過 new 分配的,則可以執行 delete this;。但是,這會使所有指向已解除分配物件的指標無效,包括 this 指標本身:在 delete this; 返回後,此類成員函式不能引用類的成員(因為這涉及隱式解引用 this),也不能呼叫其他成員函式。

這可以用於引用計數指標的成員函式中(例如,std::shared_ptr(C++11 起),當被管理物件的最後一個引用超出作用域時,該成員函式負責遞減引用計數。

class ref
{
    // ...
    void incRef() { ++mnRef; }
    void decRef() { if (--mnRef == 0) delete this; }
};

[編輯] 關鍵詞

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++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
CWG 760 C++98 this 在巢狀類中使用時,它
未指定是與
巢狀類還是封閉類關聯
this 總是與
最內層巢狀類關聯,
無論它是否在
非靜態成員函式中
CWG 2271 C++98 this 在構造
非 const 物件時可能被別名
在此情況下也
禁止別名
CWG 2869 C++98 不清楚 this 是否可以用於
非關聯類的靜態成員函式中
已明確