为什么在这个地方code崩溃提及? [英] Why does this code crash at the places mentioned?

查看:119
本文介绍了为什么在这个地方code崩溃提及?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您详细说明为什么在这个地方code崩溃提及?我有点难倒这一点。我想,它已经得到的东西做与的sizeof(INT),但我不那么肯定。有人能解释一下吗?

 类基地
{
上市:
    虚拟无效SomeFunction()
    {
        的printf(试验基地\\ n);
    }    INT m_j;
};派生类:公共基础{
上市:
   无效SomeFunction()
   {
       的printf(测试导出\\ n);
   }私人的:
   诠释m_i;
};虚空MyWonderful code(基地baseArray [])
{
   baseArray [0] .SomeFunction(); //工作正常
   baseArray [1] .SomeFunction(); //崩溃,因为无效的vfptr的
   baseArray [2] .SomeFunction(); //崩溃,因为无效的vfptr的
   baseArray [3] .SomeFunction(); //工作正常
   baseArray [4] .SomeFunction(); //崩溃,因为无效的vfptr的
   baseArray [5] .SomeFunction(); //崩溃,因为无效的vfptr的
   baseArray [6] .SomeFunction(); //工作正常
   baseArray [7] .SomeFunction(); //崩溃,因为无效的vfptr的
   baseArray [8] .SomeFunction(); //崩溃,因为无效的vfptr的
   baseArray [9] .SomeFunction(); //工作正常
}
INT _tmain(INT ARGC,TCHAR *的argv [])
{
   衍生derivedArray [10];
   MyWonderful code(derivedArray);
   返回0;
}


解决方案

报价从这个常见问题解答:的是派生一样为基础的数组的数组?


  

派生比大基地,与第二对象所做的指针运算baseArray是
  不正确:编译器使用的sizeof(基地)计算地址时,
  对于第二个对象,但数组是衍生的数组,这意味着
  计算出的地址(以及随后的调用
  构件函数f())是连在任何对象的开始!它的
  嫌中派生对象的中间。


Can you please elaborate why this code crashes at the places mentioned? I am a bit stumped on this. I guess that it has got something to do with sizeof(int) but I am not so sure. Can anybody explain?

class Base
{
public:
    virtual void SomeFunction() 
    {
        printf("test base\n");
    }

    int m_j;
};

class Derived : public Base {
public:
   void SomeFunction() 
   {
       printf("test derive\n");
   }

private:
   int m_i;
};

void MyWonderfulCode(Base baseArray[])
{
   baseArray[0].SomeFunction();  //Works fine
   baseArray[1].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[2].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[3].SomeFunction();  //Works fine
   baseArray[4].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[5].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[6].SomeFunction();  //Works fine
   baseArray[7].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[8].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[9].SomeFunction();  //Works fine
}
int _tmain(int argc, TCHAR* argv[])
{
   Derived derivedArray[10];
   MyWonderfulCode(derivedArray);
   return 0;
}

解决方案

Quote from this FAQ: Is array of derived same as as array of base?

Derived is larger than Base, the pointer arithmetic done with 2nd object baseArray is incorrect: the compiler uses sizeof(Base) when computing the address for 2nd object, yet the array is an array of Derived, which means the address computed (and the subsequent invocation of member function f()) isn’t even at the beginning of any object! It’s smack in the middle of a Derived object.

这篇关于为什么在这个地方code崩溃提及?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆