【问题标题】:Calling a subclass method causes a segmentation fault [duplicate]调用子类方法会导致分段错误[重复]
【发布时间】:2014-03-27 16:31:39
【问题描述】:

我遇到了一个奇怪的问题。我写了一个 Parent 抽象类(实现一个纯虚 test() 方法)和它的 Child 类(实现 test() 方法)。

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

        virtual bool test() const = 0;
};

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

然后,我编写了一个“Grid”类,它应该包含一个指向 Parent 的二维指针数组。该数组是使用向量库完成的:“_cells”是指向父指针的宽度*高度向量。 _cells 在 Grid 对象构造期间使用动态分配填充并在析构函数中释放。 Operator() (int a, int b) 被重载,以便能够使用以下模式调用 Parent 对象: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;
}

谢谢。

【问题讨论】:

  • 违反三规则(C++ 11 中的五),你还能期待什么?
  • 如果您想像使用g = Grid(4, 4); 一样将一个网格分配给另一个网格,最好按照三个规则为Grid 类和其他类定义operator=

标签: c++ c++11 segmentation-fault pure-virtual dynamic-allocation


【解决方案1】:

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

我建议你阅读一下the rule of three

【讨论】:

    猜你喜欢
    • 2015-01-18
    • 2021-05-25
    • 2015-07-23
    • 2016-09-24
    • 2019-12-04
    • 1970-01-01
    • 2011-06-21
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多