我怎样才能实现在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
and Bar.cpp
.
Edit 1
Note:上述代码假设使用支持 C++11 的编译器。但是,如果情况并非如此,则使用原始指针(例如,Bar* bar
)应该被使用并且destructor
必须实现才能调用delete bar
。这是避免资源泄漏所必需的;当然上面假设Foo
and Bar
对于这些类来说,拥有它们的成员指针是正确的行为,但它可以很容易地改变,这不是正确的假设。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)