C ++类和相互链接的对象形成一个循环 [英] C++ class and interlinked objects forming a cycle
问题描述
我如何实现互锁的对象结构,从而在C ++中形成一个循环
How could i achieve interlocked object structure that makes a cycle in C++
class Foo
{
Bar bar;
};
class Bar
{
Foo foo;
};
推荐答案
Foo.h
#include <memory>
class Bar; // Forward declare Bar class
class Foo
{
public:
Foo();
private:
std::unique_ptr<Bar> bar; // Use pointer so that header include is not necessary
};
Foo.cpp
#include "Foo.h"
#include "Bar.h" // Now include bar (in the cpp file to avoid circular includes)
Foo::Foo() :
bar(new Bar())
{
// Do nothing
}
对 Bar.h
和 Bar.cpp
使用相同的设置.
注意:上面的代码假定使用支持C ++ 11的编译器.但是,如果不是这种情况,则应使用原始指针(例如, Bar * bar
),并且必须强制使用 destructor
来调用 delete bar
.为避免资源泄漏,这是必需的.当然,以上假设 Foo
和 Bar
拥有它们的成员指针是这些类的正确行为,但可以轻松更改,这不是正确的假设.
Note: The above code assumes a compiler supporting C++11 is used. However, if this is not the case then a raw pointer (e.g., Bar* bar
) should be used and the destructor
must be implented to call delete bar
. This is necessary to avoid leaking the resource; of course the above assumes Foo
and Bar
owning their member pointer is the correct behavior for these classes but it can easily be changed this is not the correct assumption.
这篇关于C ++类和相互链接的对象形成一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!