【发布时间】:2018-05-28 08:45:47
【问题描述】:
我有一个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
RotationSolution.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++ 的新手,所以请原谅任何新手错误和不良做法:)
【问题讨论】:
-
为什么投反对票?请告诉我是否缺少任何东西
-
您是否错过了粘贴所有代码?你甚至没有有一个析构函数。它怎么会在那里崩溃?
-
vector包含指针时不调用delete操作,问题不在这个地方,多贴代码。
-
我们无法在我们的机器上编译它。请提供minimal reproducible example。没有它,它就是一个猜谜游戏。
PuzzlePiece.h是什么?
标签: c++ pointers destructor