【问题标题】:Program crashes when calling destructor on object with a vector matrix of pointers使用指针向量矩阵对对象调用析构函数时程序崩溃
【发布时间】: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


【解决方案1】:

RotationSolution 类中存在设计缺陷 - 它包含存储原始指针的成员变量 _matrix,并且它错过了正确定义的赋值运算符,该运算符将克隆存储在 _matrix 中的对象。 Default generated copy assigment operator 只会复制指针,这可能会导致双重释放内存和崩溃(here 是对正在发生的事情和原因的一些解释)。尝试使用“vector> > _matrix”(也可以使用#include “memory”)它应该可以解决大多数内存管理错误的问题。这里是tutorial 了解智能指针。

【讨论】:

  • 听起来像我的问题。我在调用堆栈中执行operator=。仍然不确定如何解决,但这似乎是问题所在。谢谢!
  • 对不起,在我的评论文本中不知何故弄乱了。尝试在向量模板声明中使用 std::shared_ptr 类型而不是 PuzzlePiece*,它应该有助于解决分配问题。要实例化 PuzzlePiece 对象,您可以使用 std::make_shared(... constructor parameters go here ...)
猜你喜欢
  • 2019-12-28
  • 2023-03-31
  • 1970-01-01
  • 2021-07-25
  • 2021-10-12
  • 2018-02-22
  • 2016-09-23
  • 2019-07-04
  • 2012-04-15
相关资源
最近更新 更多