Skip to content

this pointer

cppreference this pointer

Value category of this pointer

The keyword this is a prvalue expression whose value is the address of the implicit object parameter (object on which the non-static member function is being called).

NOTE: 在C++\Language-reference\Expressions\Value-categories\Value-categories.md中对此进行了解释。

在cppreference Non-static member functions 中:

unlike cv-qualification, ref-qualification does not change the properties of the this pointer: within a rvalue ref-qualified function, *this remains an lvalue expression.

*this是 **lvalue expression**是因为在cppreference Value categories 中有这样的规则:

lvalue:

*p, the built-in indirection expression;

CV of this pointer

The type of this in a member function of class X is X* (pointer to X). If the member function is cv-qualified, the type of this is cv X* (pointer to identically cv-qualified X). Since constructors and destructors cannot be cv-qualified, the type of this in them is always X*, even when constructing or destroying a const object.

NOTE: 关于CV of this pointer,在./Function-member中进行了更加详细的说明

this is dependent name

In class templates, this is a dependent expression, and explicit this-> may be used to force another expression to become dependent.

NOTE: 关于dependent expression,参见C++\Language-reference\Basic-concept\Organization\Name-lookup\Dependent-name-lookup

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
    }
};

int main()
{
    D<int> d;
}
// g++ test.cpp

NOTE: 关于this is dependent name,参见C++\Language-reference\Basic-concept\Organization\Name-lookup\Dependent-name-lookup,其中有着较好的描述。