C ++如何在内存中存储函数和对象?

问题描述:

假设我们有一个类

class A
{
 int x;
 public:
 void sayHi()
 {
  cout<<"Hi";
  }
 };

 int main()
 {
   A *a=NULL;
   a->sayHi();
 }

上述代码将在 Turbo C (其中我测试)并打印 Hi 作为输出。

The above code will compile on Turbo C(where i tested) and print Hi as output.

code> a 是 NULL 。更多的如果我使 sayHi() function virtual,它说

I was expecting crash because a is NULL. More over if i make sayHi() function virtual, it says

Abnormal temination(Segmentation fault in gcc) 

我知道很多是依赖于实现,

I know a lot of it is implementation dependent but if anybody could throw some light on any implementation or just give an overview it would be really nice.

显然,代码具有未定义的行为,即,你得到的是偶然的。也就是说,当调用非虚拟成员函数时,系统不需要知道对象:它可以基于签名被调用。此外,如果成员函数不需要访问成员,它不需要真正需要一个对象,只需运行。这是你在代码打印一些输出时观察到的。

Obviously, the code has undefined behavior, i.e., whatever you get is by chance. That said, the system doesn't need to know about the object when calling a non-virtual member function: It can just be called based on the signature. Further, if a member function doesn't need to access a member, it doesn't need really need an object at all and can just run. This is what you observed when the code printed some output. Whether this is how the system is implemented isn't defined, however, i.e., nothing says it works.

当调用一个虚拟函数类型系统时,首先查看一个类型与对象相关联的信息记录。当在 NULL 指针上调用虚函数时,没有这样的信息,并尝试访问它可能导致某种崩溃。

When calling a virtual function type system starts off looking at a type information record associated with the object. When calling a virtual function on a NULL pointer, no such information exists and attempting to access it probably leads to some sort of crash. Still, it doesn't have to but it does for most system.

BTW, main() always 返回 int