this pointer
[edit] Syntax
this
|
|||||||||
The keyword this
is a prvalue expression whose value is the address of the object, on which the member function is being called. It can appear in the following contexts:
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.
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.
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.
[edit] 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 } }; 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 }; } }