C++循环引用问题
我有 2 个类:DataObject
和 DataElement
。 DataObject
(仅)保存指向 DataElement
的指针,并且 DataElement
包含指向多种类型的指针,其中 DataObject
>。
这曾经没有问题,因为我只在 DataElement
中使用指向 DataObject
的指针,因此在 DataObject
的标头中向前声明 DataObject
code>DataElement 就足够了。
但是现在,我尝试向 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 的完整标头,因为这再次给我带来了循环依赖。
提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在包含两个标头的 .cpp 文件中定义析构函数。
Define the destructor in a .cpp file that includes both headers.
为在类体外部和第二个类之后定义的第一个类创建析构函数,例如
Make the destructor for the first class defined outside of the class body and after the second class, e.g.