【问题标题】:C++ circular reference problemC++循环引用问题
【发布时间】:2010-10-25 16:02:37
【问题描述】:

我有 2 个课程:DataObjectDataElementDataObject 包含指向(仅)DataElements 的指针,DataElement 包含指向多种类型的指针,其中 DataObject

以前没问题,因为我只在DataElement中使用了指向DataObjects的指针,所以在DataElement的头部前向声明DataObject就足够了。

不过,现在我尝试向DataElement 添加一个析构函数,其中我需要删除DataObject。对此,编译器说:

dataelement/destructor.cc: In destructor ‘DataElement::~DataElement()’:
dataelement/destructor.cc:8: warning: possible problem detected in invocation of delete operator:
dataelement/destructor.cc:8: warning: invalid use of incomplete type ‘struct DataObject’
dataelement/dataelement.h:7: warning: forward declaration of ‘struct DataObject’
dataelement/destructor.cc:8: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.

我该如何解决这个问题?前向声明显然是不够的,而我不能包含 DataObject 的完整标头,因为这又给了我一个循环依赖。

提前致谢!

【问题讨论】:

  • 考虑使用智能指针,如shared_ptr/weak_ptrscoped_ptrunique_ptr(如果您的实现支持它);这些使 C++ 中的资源管理变得更加容易,并帮助您确保您的代码是异常安全和正确的。

标签: c++ class-design destructor circular-dependency forward-declaration


【解决方案1】:

在包含两个标头的 .cpp 文件中定义析构函数。

【讨论】:

  • 谢谢,我会的。 (现在我知道解决方案非常明显,但之后总是这样:))
【解决方案2】:

为在类主体之外和第二个类之后定义的第一个类创建析构函数,例如

class DataElement;

class DataObject
{
    DataElement* elem;
public:
    ~DataObject();
};

class DataElement
{
    DataObject* obj;
public:
    ~DataElement() { delete obj; }
};

DataObject::~DataObject()
{
    delete elem;
}

【讨论】:

  • 谢谢!我会选择 James McNellis 的解决方案,因为它现在更容易做到,但这似乎也是一个很好的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多