为何C++代码调用拷贝构造/赋值运算符时触发_CrtIsValidHeapPointer断言失败?
解决_CrtIsValidHeapPointer(block)断言错误的方案
问题根源
你的代码中Oras类包含动态分配的float* istoricTemp成员,但没有显式定义拷贝构造函数和赋值运算符。编译器自动生成的默认版本只会做浅拷贝——直接复制指针地址,导致多个Oras(或继承它的Capitala)对象共享同一块堆内存。当这些对象生命周期结束调用析构函数时,会重复释放同一块内存,触发堆指针有效性断言。
修复步骤
必须为Oras类添加显式的拷贝构造函数和赋值运算符,实现深拷贝逻辑:
1. 添加Oras类的拷贝构造函数
在Oras类的public区域添加:
Oras(const Oras& other) { this->nume = other.nume; this->tara = other.tara; this->tempCrt = other.tempCrt; this->nrLuni = other.nrLuni; // 深拷贝动态数组 if (other.nrLuni > 0 && other.istoricTemp != nullptr) { this->istoricTemp = new float[other.nrLuni]; for (int i = 0; i < other.nrLuni; ++i) { this->istoricTemp[i] = other.istoricTemp[i]; } } else { this->istoricTemp = nullptr; } }
2. 添加Oras类的赋值运算符重载
同样在Oras类的public区域添加:
Oras& operator=(const Oras& other) { if (this != &other) { // 防止自赋值 // 先释放当前对象已有的动态内存 delete[] this->istoricTemp; // 拷贝非动态成员 this->nume = other.nume; this->tara = other.tara; this->tempCrt = other.tempCrt; this->nrLuni = other.nrLuni; // 深拷贝动态数组 if (other.nrLuni > 0 && other.istoricTemp != nullptr) { this->istoricTemp = new float[other.nrLuni]; for (int i = 0; i < other.nrLuni; ++i) { this->istoricTemp[i] = other.istoricTemp[i]; } } else { this->istoricTemp = nullptr; } } return *this; }
修复原理
修改后,Oras的拷贝构造和赋值操作会为每个对象分配独立的堆内存存储温度历史数据,每个对象的istoricTemp指针指向各自的内存块。当对象析构时,只会释放自己拥有的内存,不会出现重复释放同一块内存的情况,断言错误即可解决。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

