我正在试图弄清楚崩溃,并将其归结为以下示例:
class Base
{
public:
virtual unsigned int GetNum () = 0;
};
class Derived : public Base
{
int data; // <--- commmenting this out removes the crash
public:
Derived() {}
virtual unsigned int GetNum() { return 1; }
};
void func() {
Base** ppBases;
unsigned int xLen = 3;
unsigned int yLen = 4;
ppBases = new Base*[xLen];
for(unsigned int x = 0; x < xLen; ++x) {
ppBases[x] = new Derived[yLen];
for(unsigned int y = 0; y < yLen; ++y) {
Base* curBase = dynamic_cast<Base*>(&(ppBases[x][y]));
Derived* curDerived = dynamic_cast<Derived*>(&(ppBases[x][y])); // <--- crashes with a null dereference
unsigned int result = curBase->GetNum();
result = result;
}
}
}
我猜测Derived实际上并没有分配适当的大小。将ppBases更改为tripple指针(如此)会使一切正常工作:
void func() {
Base*** ppBases;
unsigned int xLen = 3;
unsigned int yLen = 4;
ppBases = new Base**[xLen];
for(unsigned int x = 0; x < xLen; ++x) {
ppBases[x] = new Base*[yLen];
for(unsigned int y = 0; y < yLen; ++y) {
ppBases[x][y] = new Derived();
Base* curBase = dynamic_cast<Base*>(ppBases[x][y]);
Derived* curDerived = dynamic_cast<Derived*>(ppBases[x][y]);
unsigned int result = curBase->GetNum();
result = result;
}
}
}
我不明白为什么。
由于
答案 0 :(得分:1)
问题在于这一行:
ppBases[x] = new Derived[yLen];
您将Derived
个对象数组分配给Base *
指针。因此,当您编写ppBases[x][y]
时,编译器将使用指针的类型(Base *
)并进行适当的索引。因此ppBases[x][1]
不会引用已分配数组中的第二个Derived
对象。