简体   繁体   English

两个类的前向声明会在构造函数中导致循环依赖吗?

[英]Will forward-declaration of two classes lead to circular dependency in the constructor?

Is this allowed? 可以吗? I am trying to determine if there is a risk of circular dependency in the constructor. 我正在尝试确定构造函数中是否存在循环依赖的风险。

Header file: 头文件:

class B; //forward declaration 

class A
{
public:
    std::unique_ptr<B> cObj;
    std::vector<B*> cList;
    A();
};

class B
{
public:
    B(A& aObj) : aObjLocal(aObj) {};
    void ShareData(int result);
private:
    A& aObjLocal;
};

Cpp file: Cpp文件:

void B::ShareData(int result)
{
    for (auto& iterator : aObjLocal.cList)
    {
        (*iterator).ShareData(result);
    }
}

A::A()
{
    cObj = std::make_unique<B>(*this); // <- Will this cause circular dependecy 
}

Thanks in advance for sharing the knowledge. 在此先感谢您分享知识。

There is no circular dependency appearing here, since B does not contain an actual object of type A but only a reference. 由于B不包含类型A的实际对象,而仅包含引用,因此这里没有出现循环依赖关系。 That way, *A::cObj has a well-defined size upon construction and does not depend on the implementation details of A (if B contained an actual A instead of a reference, a circular dependency would occur, the memory required to create an A would be infinite). 这样, *A::cObj在构造时具有明确定义的大小,并且不依赖于A的实现细节(如果B包含实际的A而不是引用,则会发生循环依赖关系,因此创建A所需的内存A将是无限的)。

Lets have a look at a small example (I made aObjLocal public just to be able to print the address): 让我们看一个小例子(我公开aObjLocal只是为了能够打印地址):

int main(){                                                                                          
 A a;                                                                                               
 std::cout << "Address of a:                   " << &a << std::endl;                                                                      
 std::cout << "Address of aObjLocal of a.cObj: " << &((*(a.cObj)).aObjLocal) << std::endl;                                                
}  

The output will look something like this 输出看起来像这样

Address of a:                   0x7ffe68b95f70
Address of aObjLocal of a.cObj: 0x7ffe68b95f70

So a.cObj does contain the correct reference to a , the code works as intended (assuming this behavior is the intended one). 因此a.cObj确实包含对a的正确引用,代码按预期工作(假设此行为是预期的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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