C++对象模型(8)-- 数据语义学:this指针

1、this指针的认识

this 是 C++ 中的一个关键字,也是一个 const 指针 ,它指向当前对象,通过它可以访问当前对象的所有成员。所谓当前对象,是指正在使用的对象。

假如有这么一个类:

class Base {
public:
    int b_i;
    int b_j;

    void print() {
        printf(" this的地址:%p\n", this);
    }
};

那么这个Base类对象的this指针指向的就是变量b_i的地址。

C++对象模型(8)-- 数据语义学:this指针_第1张图片

2、没有虚函数的情况

this指针调整一般存在于多重继承的情况下。

我们先进行代码演示:

class X {
public:
    int x_i;

    X() {
        cout << " X::X()的this指针是:" << this << endl;
    }

    void funcX() {
        cout << " X::funcX()的this指针是:" << this << endl;
    }
};

class Y {
public:
    int y_i;

    Y() {
        cout << " Y::Y()的this指针是:" << this << endl;
    }

    void funcY() {
        cout << " Y::funcY()的this指针是:" << this << endl;
    }
};

class Z : public X, public Y {
public:
    int z_i;

    Z() {
        cout << " Z::Z()的this指针是:" << this << endl;
    }

    void funcZ() {
        cout << " Z::funcZ()的this指针是:" << this << endl;
    }
};

int main()
{
    Z z;
    z.funcX();
    z.funcY();
    z.funcZ();
}

类Z对象的内存布局是这样的:

C++对象模型(8)-- 数据语义学:this指针_第2张图片

代码的输出结果是这样的:

C++对象模型(8)-- 数据语义学:this指针_第3张图片

从输出结果可以画出this指针的指向是下面这样的。

C++对象模型(8)-- 数据语义学:this指针_第4张图片

这里有2个要点:

(1) 这里Z类先继承X、再继承Y。派生类Z的地址和第1个继承的基类X的地址是相同的。

(2) 调用哪个子类的成员函数,这个this指针就会被编译器自动调整到对象内存布局中对应类对象的起始地址。

3、父类没有虚函数、子类有虚函数

class X {
public:
    int x_i;

    X() {
        cout << " X::X()的this指针是:" << this << endl;
    }

    void funcX() {
        cout << " X::funcX()的this指针是:" << this << endl;
    }
};

class Y : public X {
public:
    int y_i;

    Y() {
        cout << " Y::Y()的this指针是:" << this << endl;
    }

    void funcY() {
        cout << " Y::funcY()的this指针是:" << this << endl;
    }

    virtual void virFuncY() { }
};

int main()
{
    Y y;

    printf(" 变量a的偏移量:%d\n", &X::x_i);
    printf(" 变量c的偏移量:%d\n", &Y::y_i);

    y.funcX();
    y.funcY();
}

这时输出的结果是这样的:

C++对象模型(8)-- 数据语义学:this指针_第5张图片

从输出结果可以看到:

(1) 父类X的this指针比子类X高4个字节,类X的变量x_i的偏移量是0。

这个可以这么理解:虚函数表指针vptr总是在对象的头部,因为父类X没有虚函数表指针,所以父类X对象的指针要往下跳过vptr(4个字节),然后就直接访问变量x_i,所以x_i的偏移量是0。

(2) 类Y的变量y_i的偏移量是8。因为vptr、int x_i各占4个字节,所以变量y_i的偏移量是 4 + 4 = 8。

C++对象模型(8)-- 数据语义学:this指针_第6张图片

4、父类、子类都有虚函数

我们给类X加上虚函数:

virtual void virFuncX() { }

然后看输出结果:

C++对象模型(8)-- 数据语义学:this指针_第7张图片

从结果我们可以看到,父类X的this指针和类Y的this指针相同了,且变量x_i的偏移量变成了4。这4个字节是虚函数表指针所占用的空间。

C++对象模型(8)-- 数据语义学:this指针_第8张图片

5、多重继承且父类都带虚函数

我们在原来的代码上再添加1个新类Z,且让Z继承自类X、Y:

class Z : public X, public Y {
public:
    int z_i;

    Z() {
        cout << " Z::Z()的this指针是:" << this << endl;
    }

    void funcZ() {
        cout << " Z::funcZ()的this指针是:" << this << endl;
    }
};

int main()
{
    Z z;

    printf(" 变量x_i的偏移量:%d\n", &X::x_i);
    printf(" 变量y_i的偏移量:%d\n", &Y::y_i);
    printf(" 变量z_i的偏移量:%d\n", &Z::z_i);

    z.funcX();
    z.funcY();
    z.funcZ();
}

输出结果:

C++对象模型(8)-- 数据语义学:this指针_第9张图片

因为2个父类都有虚函数,所以类Z会继承这2个虚函数表指针。但2个父类X、Y是并级的,对于每一个父类对象来说,它的成员变量都会偏移4个字节。而子类的变量会偏移16个字节。

C++对象模型(8)-- 数据语义学:this指针_第10张图片

你可能感兴趣的:(C++对象模型,c++,对象模型,this指针)