避免循环依赖? [英] Avoiding circular dependence?

查看:203
本文介绍了避免循环依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与先前的问题相关

Related to a previous question, I have now the following one:

在下一个风景:

class B;

class A
{
   // stuff, methods and so on
   B b;
};

class B
{
   // stuff, methods and so on
   A a;
};

这里我们有一个循环依赖 A B ,但是此代码是不成形的,因为 B 是不完整的类型。解决方案是通过例如智能指针通过 B 的指针来改变 B 。但是添加指针会增加不必要的复杂性和资源,因为你不需要指针!

Here we have a circular dependence between A and B, but this code is ill-formed since B is an incomplete type. A solution is to change B by a pointer of B by means of a smart pointers for example. But adding pointer add complexity and resources spending unnecesarily since you don't need a pointer!

在上一个问题我试图避免使用指针通过模板,所以我延迟的实例化这个类在两个类都被定义的点,但是我不能成功地做。

In the previous question I tried to avoid the use of pointers by means of templates, so I delay the instantation of the class at a point where both classes are defined, but I was incapable of doing it successfuly.

避免指针是不可能的?有没有公​​知的dessign避免循环依赖?

Is it impposible to avoid pointers? Are there well-known dessigns to avoid circular dependences?

推荐答案

这是不可能避免某种形式的引用,例如指针。

It is impossible to avoid some form of reference, for example pointers.

当你尝试做它时,在定义中有一个无限递归。 A 包括 B ,其中包括 A 所以更多。因此,这两个类都需要无限的存储,这显然是荒谬的。

As you are trying it to do it, there is an infinite recursion in the definition. An A includes a B which includes and A, and so on for ever more. So, both classes would require infinite storage which is obviously nonsensical.

如果你真的有一个模型 A B B 包含 A 不能相互生活。在这种情况下,你可能只有一个类,而不是两个。

If you really have a model where A contains B and B contains A then these classes appear to be incapable of living without each other. In which case perhaps you only really have one class and not two.

这篇关于避免循环依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆