使用指针的矢量矩阵在对象上调用析构函数时程序崩溃

Program crashes when calling destructor on object with a vector matrix of pointers

本文关键字:调用 对象 析构函数 崩溃 程序 指针      更新时间:2023-10-16

我有一个class,它基本上是一个指向另一个对象的指针2D matrix的包装器,矩阵由vectors组成。

出于某种原因,每当调用我的class的析构函数时,程序都会崩溃,并且似乎它试图delete指针,即使它们nullptr,这会导致崩溃。

这是我的.h.cpp文件:

CPP 文件:

RotationSolution.h

#ifndef PUZZLESOLVER_ROTATIONSOLUTION_H
#define PUZZLESOLVER_ROTATIONSOLUTION_H
#include <vector>
#include <fstream>
#include "PuzzlePiece.h"
using namespace std;
class RotationSolution {
private:
int _height, _width;
vector<vector<PuzzlePiece*>> _matrix;
public:
RotationSolution();
RotationSolution(int height, int width);
vector<PuzzlePiece*>& operator[](int row);
int get_height() const;
int get_width() const;
};

#endif //PUZZLESOLVER_ROTATIONSOLUTION_H

旋转解决方案.cpp:

#include "RotationSolution.h"
vector<PuzzlePiece*>& RotationSolution::operator[](int row) {
return _matrix[row];
}
RotationSolution::RotationSolution() : RotationSolution(0, 0) {}
RotationSolution::RotationSolution(int height, int width) :
_height(height), _width(width), _matrix(vector<vector<PuzzlePiece*>>(_height, vector<PuzzlePiece*>(_width, nullptr)))
{}
int RotationSolution::get_height() const {
return _height;
}
int RotationSolution::get_width() const {
return _width;
}

代码实际上在如下所示的部分中崩溃:

for (auto length: _rowLengths) {
auto height = size / length;
_sol = RotationSolution(height, length);
...
}

_sol = RotationSolution(height, length);行的第二次迭代中。

调试时,发送崩溃信号的代码来自new_allocator.h(我很确定这是一个 lib 文件):

// __p is not permitted to be a null pointer.
void
deallocate(pointer __p, size_type)
{ ::operator delete(__p); }

我仍然是c++新手,所以请原谅任何菜鸟错误和不良做法:)

RotationSolution 类中存在一个设计缺陷 - 它包含存储原始指针的成员变量_matrix,并且它错过了正确定义的 assigment 运算符,该运算符将克隆存储在_matrix中的对象。默认生成的复制同化运算符将只复制指针,这可能会导致双倍释放内存和崩溃(这里有一些解释正在发生的事情和原因)。尝试使用"vector<std::shared_ptr>>> _matrix"(也 #include"memory"),它应该可以解决大多数错误的内存管理问题。这是阅读智能指针的教程。