C++ circular reference problem

纵饮孤独 提交于 2019-12-31 06:53:21

问题


I have 2 classes: DataObject and DataElement. DataObject holds pointers to (only) DataElements, and a DataElement contains pointers to several types, among which a DataObject.

This used to be no problem, since I only use pointers to DataObjects in DataElement, so a forward declaration of DataObject in the header of DataElement is enough.

Now, however, I try to add a destructor to DataElement, in which I need a delete on a DataObject. On this the compiler says:

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.

How can I solve this? A forward declaration is apparently not enough, while I cannot include the complete header for DataObject, since that gives me a circular dependency again.

Thanks in advance!


回答1:


Define the destructor in a .cpp file that includes both headers.




回答2:


Make the destructor for the first class defined outside of the class body and after the second class, e.g.

class DataElement;

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

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

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


来源:https://stackoverflow.com/questions/4016471/c-circular-reference-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!