C++ 当对具有指针向量矩阵的对象调用析构函数时,程序崩溃
我有一个C++ 当对具有指针向量矩阵的对象调用析构函数时,程序崩溃,c++,pointers,destructor,C++,Pointers,Destructor,我有一个类,它基本上是指向另一个对象的指针的2D矩阵的包装器,矩阵由向量组成 出于某种原因,每当调用my类的析构函数时,程序就会崩溃,并且它似乎试图删除指针,即使它们是nullptr,这会导致崩溃 这是我的.h和.cpp文件: cpp文件: #include "RotationSolution.h" vector<PuzzlePiece*>& RotationSolution::operator[](int row) { return _matrix[row]; }
类
,它基本上是指向另一个对象的指针的2D矩阵
的包装器,矩阵由向量
组成
出于某种原因,每当调用my类的析构函数时,程序就会崩溃,并且它似乎试图删除指针,即使它们是nullptr
,这会导致崩溃
这是我的.h
和.cpp
文件:
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;
}
旋转解决方案.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
在\u sol=旋转解(高度、长度)的第二次迭代中代码>行
调试时,发送崩溃信号的代码来自new\u allocator.h
(我很确定这是一个lib文件):
我对c++
还是个新手,所以请原谅任何noob错误和错误做法:)RotationSolution类中存在一个设计缺陷-它包含存储原始指针的成员变量_matrix,它缺少正确定义的assignment操作符,该操作符将克隆存储在_matrix中的对象。将只复制可能导致双重释放内存和崩溃的指针(这是一些正在发生的情况和原因的解释)。尝试使用“vector>>_matrix”(也包括“memory”),它应该可以解决大多数错误内存管理的问题。以下是有关智能指针的信息。为什么要投否决票?请告诉我是否有什么遗漏您是否错过了粘贴所有代码?你甚至没有析构函数。它怎么会在那里崩溃呢?请发布一个。当向量包含指针时不调用delete运算符,问题不在这里,请粘贴更多代码。我们无法在我们的机器上编译。请提供一份报告。没有它,这是一个猜谜游戏。什么是PuzzlePiece.h
?听起来像是我的问题。我在调用堆栈中执行操作符=
。虽然仍然不确定如何修复,但这似乎是个问题。谢谢抱歉,在我的评论文本中,不知怎么搞砸了。尝试在向量模板声明中使用std::shared_ptr type而不是PuzzlePiece*,这将有助于解决分配问题。要实例化拼图块对象,可以使用std::make_shared(…构造函数参数在这里…)
for (auto length: _rowLengths) {
auto height = size / length;
_sol = RotationSolution(height, length);
...
}
// __p is not permitted to be a null pointer.
void
deallocate(pointer __p, size_type)
{ ::operator delete(__p); }