C++对象模型 ch4 Function语义学

1. name mangling

代码如下:

/home/a/j/nomad2:cat Point.CPP #include <iostream> using namespace std; class Point { private: int pinx; int piny; public: void foo() { cout << (pinx + piny) << endl; } int foo(int arg) { cout << (pinx + piny) << endl; } static void func() { cout << "hi dude" << endl; } }; int main() { Point p; p.foo(); p.foo(2); ((Point*)0)->func(); }
查看函数的新名,

/home/a/j/nomad2:nm a.out |grep foo [79] | 68320| 56|FUNC |GLOB |0 |9 |_ZN5Point3fooEi [82] | 68256| 48|FUNC |GLOB |0 |9 |_ZN5Point3fooEv /home/a/j/nomad2:nm a.out |grep func [69] | 68392| 44|FUNC |GLOB |0 |9 |_ZN5Point4funcEv

2. Virtual table

There are three possibilities:

1. It can inherit the instance of the virtual function declared within the base class. Literally, the address of that instance is copied into the associated slot in the derived class's virtual table.

2. It can override the instance with one of its own. In this case, the address of its instance is placed within the associated slot.

3. It can introduce a new virtual function not present in the base class. In this case, the virtual table is grown by a slot and the address of the function is placed within that slot.

So if we have the expression

ptr->z();


how do we know enough at compile time to set up the virtual function call?

In general, we don't know the exact type of the object ptr addresses at each invocation of z(). We do know, however, that through ptr we can access the virtual table associated with the object's class.

Although we again, in general, don't know which instance of z() to invoke, we know that each instance's address is contained in slot 4.

This information allows the compiler to internally transform the call into

( *ptr->vptr[ 4 ] )( ptr );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值