我面临着一个奇怪的问题。我写了一个父抽象类(实现纯虚拟test()方法)及其子类(实现test()方法)。

class Parent
{
    public :
        Parent();
        virtual ~Parent() = default;

        virtual bool test() const = 0;
};

class Child : public Parent
{
    public :
        bool test() const;
};

然后,我写了一个"网格"类,它应该包含一个指向父级的二维指针数组。数组是使用向量库完成的 :"_cells"是指向父指针的宽度*高度向量。_cells在网格对象构造期间使用动态分配填充,并在析构函数中释放。Operator()(int a,int b)被重载,以便能够使用此模式调用父对象 :myGrid(x,y)。

class Grid
{
        int _w, _h;
        std::vector<Parent*> _cells;

    public :
        Grid(int w = 0, int h = 0);
        ~Grid();
        Parent* &operator()(int x, int y);

    private :
        void generate();
};

在我的主函数中,g是在堆栈上创建的第一个2x2网格。然后,它应该破坏g并在g中构建一个新的4x4网格。但它完全失败了 :

Grid g(2, 2);
std::cout << g(1,1)->test() << std::endl; // Works perfectly
g = Grid(4, 4); // Probably wrong, but don't throw an exception
std::cout << g(1,1)->test() << std::endl; // SIGSEGV

我认为问题来自每个单元格的动态分配/取消分配,但我没有找到解决它的方法。

这是我的完整代码,我没有成功地简化它。我已经尽力了不好意思。。。.

#include <iostream>
#include <cstdlib>
#include <vector>

class Parent
{
    public :
        Parent();
        virtual ~Parent() = default;

        virtual bool test() const = 0;
};

Parent::Parent()
{}

class Child : public Parent
{

    public :
        bool test() const;
};

bool Child::test() const
{
    return true;
}

class Grid
{
        int _w, _h;
        std::vector<Parent*> _cells;

    public :
        Grid(int w = 0, int h = 0);
        ~Grid();
        Parent* &operator()(int x, int y);

    private :
        void generate();
};

Grid::Grid(int w, int h) : _w(w), _h(h), _cells(w*h)
{
    generate();
}

Grid::~Grid()
{
    for (auto cell : _cells)
        delete cell;
}

Parent* &Grid::operator()(int x, int y)
{
    return _cells[x*_w+y];
}

void Grid::generate()
{
    int cell_num;
    for (cell_num = 0; cell_num < static_cast<int>(_cells.size()); cell_num++)
        _cells[cell_num] = new Child();
}

int main()
{
    Grid g(2, 2);
    std::cout << g(1,1)->test() << std::endl;
    g = Grid(4, 4);
    std::cout << g(1,1)->test() << std::endl;

    return 0;
}

谢谢.

有帮助吗?

解决方案

Grid 类没有复制赋值运算符,因此将使用编译器默认生成的版本。这是非常简单的,并且只做成员的浅副本。这意味着为 临时性的 对象 Grid(4, 4) 被复制(只是指针,而不是它们指向的),当临时对象被销毁时,指针也是如此(在临时对象的析构函数中)。这给你留下了一个对象 g 带有指向现在已删除内存的指针。

我建议你读读 三法则.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top