使用指针的矢量矩阵在对象上调用析构函数时程序崩溃
Program crashes when calling destructor on object with a vector matrix of pointers
我有一个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
相关文章:
- 是什么让放置新调用对象的构造函数?
- 当我调用对象的方法时,对象的成员会发生变化
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 如何从构造函数副本 T(const T&)调用对象 T?
- C++17 如何保存泛型可调用对象以供以后使用
- 检查模板中 nullptr 的函数指针,了解任何类型的可调用对象
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- 如何在C++中将可调用对象放入地图中?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 广义 std::function (std::any 表示可调用对象)
- c++ 替换调用对象方法的宏函数
- 将可调用对象传递给采用 std::function 的构造函数
- 双指针在使用 new 时不调用对象构造函数
- 可调用对象作为默认模板参数
- 只需调用对象即可获取对象数据
- 如果用户尝试从 JS 调用对象的未定义函数C++则回调C++代码
- 如何将当前替代类型的 std::variant 传递给可调用对象?
- C++对象本身作为参数调用对象的方法
- 从移交的类调用对象