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 );
本文探讨了C++中名称重整的概念及其实现原理,并详细解释了虚函数表的工作机制,包括继承时如何处理虚函数实例,以及如何通过指针调用虚函数。
483

被折叠的 条评论
为什么被折叠?



