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

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

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++还是个新手,所以请原谅任何新手的错误和不良做法:)

RotationSolution class 中存在设计缺陷 - 它包含存储原始指针的成员变量 _matrix,并且缺少正确定义的赋值运算符,该运算符将克隆存储在 _matrix 中的对象。 Default generated copy assigment operator will just copy pointers which may lead to double freeing memory and crash (here is some explanations what is happening and why). Try to use "vector< vector< std::shared_ptr< PuzzlePiece > > > _matrix" (also do #include "memory") it should fix most of problems with wrong memory management. Here is tutorial 了解智能指针。