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 限定符,因此其中 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; } };
[编辑] 关键词
[编辑] 示例
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 是否可以用于 非关联类的静态成员函数中 |
已明确 |