首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

this pointer

句法

this

?

?

关键词this是prvalue表达其值为调用成员函数的对象的地址。它可以出现在以下上下文中:

1%29内的任何非静电体成员函数,包括成员初始化列表

2%29声明在%28可选%29 cv-限定符序列之后的任何位置,包括动态异常规范28%被反对的人占29%,除规格外%28C++11%29,尾随返回类型%28自C++11%29

3%29默认成员初始化器%28自C++11%29

类型this在类的成员函数中XX*%28指针到X%29。如果成员函数是简历-合格,类型thiscv X*%28指针指向相同的cv-限定X%29。由于构造函数和析构函数不能被cv限定,所以this在他们里面总是X*,即使在构造或破坏Const对象时也是如此。

在任何上下文中使用非静态类成员时,this关键字允许%28非静态成员函数体、成员初始化程序列表、默认成员初始化器%29、隐式成员初始化项。this->在名称之前自动添加,从而生成成员访问表达式%28,如果成员是虚拟成员函数,则会导致调用%29的虚拟函数。

在类模板中,this是依赖表达,以及显式this->可用于强制另一个表达式成为依赖项。

施工期间对象的值,如果对象或其任何子对象的值是通过不是直接或间接从构造函数%27s获得的glvalue访问的。this指针,因此获得的对象或子对象的值未指定。换句话说,不能在构造函数中别名此指针:

二次

代码语言:javascript
复制
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;返回时,该成员函数不能引用类%28的成员,因为这涉及到this%29并且不能调用其他成员函数。例如,在控件块的成员函数中使用std::shared_ptr当对托管对象的最后一次引用超出作用域时,负责减少引用计数。

二次

代码语言:javascript
复制
class ref
{
    // ...
    void incRef() { ++mnRef; }
    void decRef() { if (--mnRef == 0) delete this; }
};

二次

二次

代码语言:javascript
复制
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
        };
    }
}

二次

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com