查看单个帖子
  #1 (permalink)  
旧 2008-07-25
liuxinyu 的头像
liuxinyu liuxinyu 当前离线
高级会员
 
注册日期: 2006-02-09
帖子: 311
文章: 49
liuxinyu 正向着好的方向发展
默认 为什么会crash?

非常短的程序,我没有想明白原因
c++ 代码:
  1. #include <iostream>
  2.  
  3. class Base1{
  4. public:
  5.   virtual ~Base1(){}
  6. };
  7.  
  8. class Base2{
  9. public:
  10.   virtual void f()=0;
  11.   //virtual ~Base2(){}
  12. };
  13.  
  14. class Derive: public Base1, public Base2{
  15. public:
  16.   void f(){ std::cout<<"f\n"; }
  17.   ~Derive(){ std::cout<<"Derive dtor\n"; }
  18. };
  19.  
  20. void func(Base2* p){
  21.   p->f();
  22. }
  23.  
  24. int main(int, char**){
  25.   Derive* p = new Derive;
  26.   Base1* pb1=p;
  27.   Base2* pb2=p;
  28.   func(p);
  29.   //delete p;
  30.   //delete pb1;
  31.   delete pb2;
  32. }

我把Base2中的虚dtor干掉后,程序crash了,但是如果我把f一同干掉,又不crash
liuuuxin@WEIFANG ~/temp
$ g++ foo.cpp

liuuuxin@WEIFANG ~/temp
$ ./a
f
8 [sig] a 3292 _cygtls::handle_exceptions: Error while dumping state (prob
ably corrupted stack)
Segmentation fault (core dumped)

想不通道理了。
回复时引用此帖