geeksforgeeks 021-c++中的this指针

函数调用链

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
using namespace std;

class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
Test obj1(5, 5);


// as the same object is returned by reference
obj1.setX(10).setY(20);

obj1.print();
return 0;
}

Output:

1
x = 10 y = 20

对于一个类X,this指针是X const
如果一个成员函数X被声明为const,this指针为const X
const

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
class X {
void fun() const {
// this is passed as hidden argument to fun().
// Type of this is const X*
}
};
#include<iostream>
class X {
void fun() volatile {
// this is passed as hidden argument to fun().
// Type of this is volatile X*
}
};
#include<iostream>
class X {
void fun() const volatile {
// this is passed as hidden argument to fun().
// Type of this is const volatile X*
}
};

delete最好不要用在this指针上面,如果使用,需要考虑下面的情况

  1. delete操作只对使用了new的对象有效

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    class A
    {
    public:
    void fun()
    {

    delete this;
    }
    };

    int main()
    {
    /* Following is Valid */
    A *ptr = new A;
    ptr->fun();
    ptr = NULL // make ptr NULL to make sure that things are not accessed using ptr.


    /* And following is Invalid: Undefined Behavior */
    A a;
    a.fun();

    getchar();
    return 0;
    }
  2. delete之后,所有的成员都不可以访问

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #include<iostream>
    using namespace std;

    class A
    {
    int x;
    public:
    A() { x = 0;}
    void fun() {
    delete this;

    /* Invalid: Undefined Behavior */
    cout<<x;
    }
    };