c++ - 使用指针 vector 矩阵调用对象的析构函数时程序崩溃

标签 c++ pointers destructor

我有一个,它基本上是指向另一个对象的指针的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/

相关文章:

c++ - 优化循环性能

c - 使用for循环分配内存

复制字符串 - 如何处理内存泄漏和错误情况?

Java,当对象的作用域结束时执行一个方法

c++ - 构造函数 c++ 对象 obj = 对象 ("string", 22);创建一个临时对象?

c++ - Boost变体模糊构造

c++ - 如何从传递给友好类构造函数的 lambda 访问私有(private)成员?

c++ - 在字符串中输入换行符

c++ - 将 `char []` 传递给接受 `std::string&` 的函数是好习惯吗

c++ - 如果调用了子类的析构函数,是否可以停止调用其基类的析构函数?