我试图找出崩溃的原因,并将其归结为以下示例:
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;
}
}
}
我猜想“派生”实际上没有分配适当的大小。将ppBases更改为三重指针(像这样)可以使所有工作正常:
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;
}
}
}
我不明白为什么。
谢谢
最佳答案
问题在于此行:
ppBases[x] = new Derived[yLen];
您正在将
Derived
对象数组分配给Base *
指针。因此,当您编写ppBases[x][y]
时,编译器将使用指针的类型(即Base *
)并适当地进行索引。因此,ppBases[x][1]
不引用分配的数组中的第二个Derived
对象。