如何修复基类中的内存分配错误
How to fix a memory allocation error in a base class?
我编写了一个包含两个类的程序。基类包括其派生类的指针对象。然后在基类的构造函数中初始化指针对象。
My Compiler在编译过程中没有给我错误,但是当控制台窗口出现时,程序崩溃,为派生类的对象给出UNHANDLED EXCEPION BAD ALLOCATION
的错误。我该怎么做才能修好它?
代码如下:
class x;
class y
{
private:
x *objx; // here is the error
...........................
};
class x: public y
{
...........................
................
};
y::y()
{
objx=new x(); // bad allocation and the program crashes
// I have also tried this way by commenting objx=new x();
*objx=0; // but still the program crashes.
}
由于调用派生类中的构造函数将调用父类中的构造函数,因此看起来您将在那里遇到递归构造问题-这可能是导致异常的原因。
为了避免这种情况,您可以将"new x()"从构造函数中移到它自己的函数中。
正如在另一个答案中解释的那样,您有一个无限递归构造问题。您可以尝试在构造函数中将指针设置为空,并创建一个方法init,该方法将生成实际的对象:
y::y()
{
// *objx=0; // this is wrong, you don't want to dereference your pointer.
objx = 0; // this should work
}
void y::init()
{
objx = new x();
}
相关文章:
- Win32编译器选项和内存分配
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 当需要超过16GB的连续内存时,内存分配失败
- 尝试摆脱任何堆内存分配
- 以下代码执行哪种内存分配(动态或静态)?
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 使用 NTAllocateVirtualMemory 和 GetProcAddress 的内存分配问题不起作用
- C++:矢量分配器行为、内存分配和智能指针
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- Linux C++ 中的页面对齐内存分配
- 整数内存分配/释放
- 将内存分配返回值强制转换为 TYPE 数组
- C++程序什么都不做,但瓦尔格林德显示内存分配
- 给定特定内存地址的数组的动态内存分配
- 如何完成内存分配
- 我刚刚了解了C++中的动态内存分配
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- 对于堆上的页面对齐内存分配是否有任何优化或不同的 API?
- 无法删除布尔动态内存分配