this
指针
来自 cppreference.cn
目录 |
[编辑] 语法
this
|
|||||||||
表达式 this 是一个 纯右值 表达式,其值是隐式对象形参的地址(在其上调用隐式对象成员函数的对象)。它可以出现在以下上下文中
3) 在 默认成员初始化器 中。
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 限定符声明,因此即使在构造或销毁 const 对象时,它们中 this 的类型始终为 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 指针获得的泛左值访问对象或其任何子对象的值,则由此获得的对象或子对象的值是不确定的。换句话说,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
的隐式解引用),并且不得调用任何其他成员函数。
这可以在引用计数指针的成员函数中使用(例如,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 可以被别名化 |
别名化也是 在这种情况下被禁止 |
CWG 2869 | C++98 | 不清楚是否可以在 非关联类的静态成员函数中使用 this |
已明确 |