我有一个类
,它基本上是指向另一个对象的指针的2D矩阵
的包装器,矩阵由 vector
组成.
由于某些原因,每当调用我的类
的析构函数时,程序就会崩溃,而且它似乎正在尝试删除
指针,即使它们是nullptr
,这会导致崩溃。
这是我的.h
和.cpp
文件:
cpp文件:
旋转解决方案.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,并且缺少正确定义的赋值运算符,该运算符将克隆存储在 _matrix 中的对象。 Default generated copy assigment operator只会复制指针,这可能会导致双重释放内存和崩溃(here 是对正在发生的事情和原因的一些解释)。尝试使用“vector< vector< std::shared_ptr< PuzzlePiece >> > _matrix”(也执行#include "memory")它应该可以解决大部分内存管理错误的问题。这是 tutorial阅读智能指针。
关于c++ - 使用指针 vector 矩阵调用对象的析构函数时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47810341/