装饰器设计模式,分段错误

Decorator Design Pattern, Segmentation fault

本文关键字:分段 错误 设计模式      更新时间:2023-10-16

我想实现装饰器设计模式。但是,我的代码给了我Segmentation fault错误。我尝试使用 -g 标志编译它,然后用 gdb 检查它。 gdb仅显示错误在action方法中的某个地方,但我不明白在哪里以及为什么。

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
class CComponent
{
protected:
    int * i_array;
    int i_size;
public:
    CComponent(int i_size)
    {
        this->i_size=i_size;
        i_array= new int[i_size];
        for(int i=0; i<i_size; i++)
        {
            i_array[i]=0;
        }
    }
    virtual int action() = 0;
    ~CComponent()
    {
        delete i_array;
    }
    int get_i_size()
    {
        return i_size;
    }
    int get_array_at(int index)
    {
        return i_array[index];
    }
};
class CConcreteCComponent : public CComponent
{
public:
    CConcreteCComponent(int i_size) : CComponent(i_size) { }
    int action()
    {
        for(int i=0; i<i_size; i++)
        {
            i_array[i] = rand() % 100;
            cout<< i_array[i] << " " << endl;
        }
        return 0;
    }
};
class Decorator : public CComponent
{
protected:
    CComponent * c;
public:
    Decorator(int i_size) : CComponent(i_size)
    {
        c = new CConcreteCComponent(100);
    }
    int action()
    {
        return c->action();
    }
};
class CConcreteDecorator3 : public Decorator
{
public:
    CConcreteDecorator3(int i_size) : Decorator(i_size)
    {
    }
    int action()
    {
        int w = action();
        for(int i=0; i<c->get_i_size(); i++)
            if(c->get_array_at(i) % 2 == 0)
                return w;
        return w + 50;
    }
};
class CConcreteDecorator1 : public Decorator
{
public:
    CConcreteDecorator1(int i_size) : Decorator(i_size)
    {
    }
    int action()
    {
        int w = action();
        if(c->get_array_at(0) == 0 && c->get_array_at(i_size -1) == 0)
            return w + 100;
        return w;
    }
};
class CConcreteDecorator2 : public Decorator
{
public:
    CConcreteDecorator2(int i_size) : Decorator(i_size)
    {
    }
    int action()
    {
        int w = action();
        if(c->get_i_size() > 7)
            return w + 150;
        return w;
    }
};
int main()
{
    Decorator * d = new CConcreteDecorator3(100);
    Decorator * d2 = new CConcreteDecorator1(100);
    Decorator * d3 = new CConcreteDecorator2(100);
    int res;
    res = d->action();
    cout << "res :" << res << endl;
    return 0;
}

原因是无限回避。

CConcreteDecorator3 中的操作方法中,而不是:

int w = action();

您可能应该使用:

int w = Decorator::action();

此外...

  1. 您的装饰器类泄漏。您没有带有删除的析构函数。
  2. 使用
  3. std::vector<int> 代替 int * i_array 和 std::unique_ptr 被认为是很好的做法,CComponent * c; 除非你无法避免,否则不要打扰使用 new/delete。
  4. 您的 CComponent 需要一个虚拟析构函数。如果你谷歌多态性和虚拟析构函数,你会发现很多解释。