繁体   English   中英

成员函数调用和 C++ 对象模型

[英]Member Function Call and the C++ Object Model

考虑下面的代码,该代码旨在研究如何进行成员函数调用以及它与 C++ 的对象模型的关系:

struct A {
  int a_;
};
struct B : A {
  int b_;
  void f();
};
void B::f() {
  std::cout << "this\t" << std::hex << this << '\n';
}
struct C: B {
  int c_;
};
int main()
{
  C c;
  C* pc = &c;
  std::cout << "&c\t" << std::hex << pc << '\n';
  pc->f();
  return 0;
}

基于 C++ 对象模型,对象c将具有对象布局:

  -------
 | a_    |
 |------ |
 | b_    |
 |------ |
 | c_    |
  -------

和,

  1. B::f()将被转换为void f(B *const)
  2. pc->f()将被转换为void f(pc + offset(b_)) ,其中offset(b_)表示c中子对象B的偏移量。

因此,根据上述观察,输出应为:

&c     address_of_c
this   address_of_c + sizeof(a_) = address_of_c + 4

但是我得到的是两者的相同地址(我使用的是 g++ 9.2):

&c      0xffffcc0c
this    0xffffcc0c

我不清楚为什么? 有人可以解释一下吗?

仅供参考:Bjarne Stroustrup 有一篇关于此的文章; 更具体地说,您可以参考第 4.2 节(第 373 页):

https://www.usenix.org/legacy/publications/compsystems/1989/fall_stroustrup.pdf

谢谢!

C 类只继承一个 B 类。所以你有

struct B
   ^
   |
   |
struct C

当创建类 C 的对象时,类 B 的子对象被放置在为类 C 的对象分配的内存的开头。

在 B 类的对象中,有一个 A 类的子对象。

您可以通过以下方式想象 C 类对象的放置

struct B b;
int c_;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM