简体   繁体   中英

C++ circular reference problem

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

This used to be no problem, since I only use pointers to DataObject s 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!

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

Make the destructor for the first class defined outside of the class body and after the second class, eg

class DataElement;

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM