我正在將一些代碼移植到Windows並且難倒了。有一些代碼在啓動時自動運行,以便將指針複製到指針,並在退出時再次運行以刪除指向指針的指針(如果它不爲空)。指針不指向指針時發生指針崩潰
我創建了一個示例程序來重現行爲
int main()
{
// Pointer to a Pointer, current crash.
InterfaceClass** ptrptr;
ConcreteTwo* object = new ConcreteTwo();
ptrptr = (InterfaceClass**)(&object); // cast is required for some reason.
delete *ptrptr; // Crash here.
// Single pointer, works fine.
InterfaceClass* ptrptr;
ConcreteTwo* object = new ConcreteTwo();
ptrptr = object;
delete ptrptr;
// There are other cases where there are only 3 classes in the hierarchy.
// This also works fine.
InterfaceClass** ptrptr;
ConcreteOne* object = new ConcreteOne();
ptrptr = (InterfaceClass**)(&object);
delete *ptrptr;
return 0;
}
的類層次結構看起來是這樣的。基類是一些帶有一些純虛函數的接口,並且被整個程序中的許多類所包含,使得許多對象可能從多個地方繼承它。正因爲如此,具體實現必須用「公共虛擬接口類」擴展它。在這個例子中,刪除「虛擬」解決了崩潰。
class InterfaceClass {
public:
virtual ~InterfaceClass() {};
InterfaceClass() {}
};
class ConcreteClass : public virtual InterfaceClass {
public:
ConcreteClass() { }
virtual ~ConcreteClass() {}
};
class ConcreteOne : public ConcreteClass
{
public:
ConcreteOne(void) {}
virtual ~ConcreteOne(void) {}
};
class ConcreteTwo : public ConcreteOne
{
public:
ConcreteTwo(void) {}
virtual ~ConcreteTwo(void) {}
};