Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/language/this"

From cppreference.com
< cpp‎ | language
m (tt title)
(Added CWG issue #760 DR.)
Line 4: Line 4:
 
===Syntax===
 
===Syntax===
 
{{sdsc begin}}
 
{{sdsc begin}}
{{sdsc | {{ttb|this}} }}
+
{{sdsc|{{ttb|this}}}}
 
{{sdsc end}}
 
{{sdsc end}}
  
The keyword {{tt|this}} is a {{rlp|value_category|prvalue}} {{rlp|expressions|expression}} whose value is the address of the {{rlp|overload resolution|implicit object parameter}} (object on which the non-static member function is being called). It can appear in the following contexts:
+
The keyword {{tt|this}} is a {{rev inl|until=c++11|{{rlp|value category#rvalue|rvalue}}}}{{rev inl|since=c++11|{{rlp|value category#prvalue|prvalue}}}} {{rlp|expressions|expression}} whose value is the address of the {{rlp|overload resolution#Implicit object parameter|implicit object parameter}} (object on which the non-static member function is being called). It can appear in the following contexts:
 
@1@ Within the body of any non-static {{rlp|member functions|member function}}, including {{rlp|initializer list|member initializer list}}
 
@1@ Within the body of any non-static {{rlp|member functions|member function}}, including {{rlp|initializer list|member initializer list}}
 
@2@ within the {{rlp|function|declaration}} of a non-static member function anywhere after the (optional) cv-qualifier sequence, including
 
@2@ within the {{rlp|function|declaration}} of a non-static member function anywhere after the (optional) cv-qualifier sequence, including
{{rrev|until=c++17|* {{rlp|except_spec|dynamic exception specification}},}}
+
{{rrev|until=c++17|* {{rlp|except spec|dynamic exception specification}},}}
 
{{rrev|since=c++11|
 
{{rrev|since=c++11|
* {{rlp|noexcept_spec|noexcept specification}}, and
+
* {{rlp|noexcept spec|noexcept specification}}, and
 
* the trailing return type
 
* the trailing return type
 
}}
 
}}
  
 
{{rrev|since=c++11|
 
{{rrev|since=c++11|
@3@ within {{rlp|data_members#Member_initialization|default member initializer}}
+
@3@ within {{rlp|data members#Member initialization|default member initializer}}
 
}}
 
}}
  
The type of {{tt|this}} in a member function of class {{tt|X}} is {{tt|X*}} (pointer to X). If the member function is {{rlp|member_functions|cv-qualified}}, the type of {{tt|this}} is {{tt|cv X*}} (pointer to identically cv-qualified X). Since constructors and destructors cannot be cv-qualified, the type of {{tt|this}} in them is always {{tt|X*}}, even when constructing or destroying a const object.
+
{{tt|this}} can only associate with the innermost enclosing class of its appearance, even if the appearance is invalid in the context:
 +
{{source|1=
 +
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
 +
        };
 +
    }
 +
}
 +
}}
 +
 
 +
The type of {{tt|this}} in a member function of class {{tt|X}} is {{tt|X*}} (pointer to X). If the member function is {{rlp|member functions#member functions with cv-qualifiers|declared with a cv-qualifier sequence}} ''cv'', the type of {{tt|this}} is {{tt|''cv'' X*}} (pointer to identically cv-qualified X). Since constructors and destructors cannot be declared with cv-qualifiers, the type of {{tt|this}} in them is always {{tt|X*}}, even when constructing or destroying a const object.
  
 
When a non-static class member is used in any of the contexts where the {{tt|this}} keyword is allowed (non-static member function bodies, member initializer lists, default member initializers), the implicit {{ttb|this->}} is automatically added before the name, resulting in a member access expression (which, if the member is a virtual member function, results in a virtual function call).
 
When a non-static class member is used in any of the contexts where the {{tt|this}} keyword is allowed (non-static member function bodies, member initializer lists, default member initializers), the implicit {{ttb|this->}} is automatically added before the name, resulting in a member access expression (which, if the member is a virtual member function, results in a virtual function call).
Line 38: Line 57:
 
     {
 
     {
 
         // var = 1;    // error: 'var' was not declared in this scope
 
         // var = 1;    // error: 'var' was not declared in this scope
         this->var = 1; // ok
+
         this->var = 1; // OK
 
     }
 
     }
 
};
 
};
Line 51: Line 70:
 
     int a, b;
 
     int a, b;
 
};
 
};
D d = D(1);   // because b(d.a) did not obtain a through this, d.b is now unspecified
+
D d = D(1); // because b(d.a) did not obtain a through this, d.b is now unspecified
 
}}
 
}}
  
Line 70: Line 89:
 
===Example===
 
===Example===
 
{{source
 
{{source
|  
+
|
| code=
+
|code=
 
class T
 
class T
 
{
 
{
Line 84: Line 103:
 
     void foo() const
 
     void foo() const
 
     {
 
     {
//       x = 7; // Error: *this is constant
+
//     x = 7; // Error: *this is constant
 
     }
 
     }
  
Line 94: Line 113:
  
 
     int y;
 
     int y;
     T(int x) : x(x), // uses parameter x to initialize member x
+
     T(int x) : x(x),     // uses parameter x to initialize member x
 
               y(this->x) // uses member x to initialize member y
 
               y(this->x) // uses member x to initialize member y
 
     {}
 
     {}
  
     T& operator= ( const T& b )
+
     T& operator=(const T& b)
 
     {
 
     {
 
         x = b.x;
 
         x = b.x;
Line 104: Line 123:
 
     }
 
     }
 
};
 
};
 
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
 
        };
 
    }
 
}
 
 
}}
 
}}
 +
 +
===Defect reports===
 +
{{dr list begin}}
 +
{{dr list item|wg=cwg|dr=760|std=C++98|before=when {{tt|this}} is used in a nested class, it was unspecified whether<br>it is associated with the nested class or the enclosing class|after={{tt|this}} always associates with<br>the innermost nested class,<br>regardless of whether it is in<br>a non-static member function}}
 +
{{dr list end}}
  
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}

Revision as of 18:47, 27 April 2022

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
 

Syntax

this

The keyword this is a rvalue(until C++11)prvalue(since C++11) expression whose value is the address of the implicit object parameter (object on which the non-static member function is being called). It can appear in the following contexts:

1) Within the body of any non-static member function, including member initializer list
2) within the declaration of a non-static member function anywhere after the (optional) cv-qualifier sequence, including
(until C++17)
(since C++11)
(since C++11)

this can only associate with the innermost enclosing class of its appearance, even if the appearance is invalid in the context:

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

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

When a non-static class member is used in any of the contexts where the this keyword is allowed (non-static member function bodies, member initializer lists, default member initializers), the implicit this-> is automatically added before the name, resulting in a member access expression (which, if the member is a virtual member function, results in a virtual function call).

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

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

During construction of an object, if the value of the object or any of its subobjects is accessed through a glvalue that is not obtained, directly or indirectly, from the constructor's this pointer, the value of the object or subobject thus obtained is unspecified. In other words, the this pointer cannot be aliased in a constructor:

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

It is possible to execute delete this;, if the program can guarantee that the object was allocated by new, however, this renders every pointer to the deallocated object invalid, including the this pointer itself: after delete this; returns, such member function cannot refer to a member of a class (since this involves an implicit dereference of this) and no other member function may be called.

This is used, for example, in the member function of the control block of std::shared_ptr responsible for decrementing the reference count, when the last reference to the managed object goes out of scope.

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

Example

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

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
CWG 760 C++98 when this is used in a nested class, it was unspecified whether
it is associated with the nested class or the enclosing class
this always associates with
the innermost nested class,
regardless of whether it is in
a non-static member function