gpt4 book ai didi

c++ - 循环依赖通常会花费很多时间来编译吗?

转载 作者:行者123 更新时间:2023-11-28 07:45:10 25 4
gpt4 key购买 nike

编辑:修改后的头文件带有守卫。我忘了把那些放在这个例子中。尽管我的项目中已经有了这些。

我有这两个类。

文件 a.h:

#ifdef A_H
#define A_H
#include "b.h"
#include "x.h" //not related to problem, is just included
class B; //fwd declaration, needed to use getB() outside of A
class A
{
public:
A(X &x);
B &getB();
...
private:
X &x;
}
#endif

文件 b.h:

#ifdef B_H
#define B_H
#include "x.h"
class A; //fwd declaration
class B
{
public:
B(X &x, A &a);
void methodThatUsesA();
...
private:
X &x;
A &a;
}
#endif

文件 a.cpp:

#include "a.h"
#include "b.h"
A::A(X &x):x(x){}
B& A::getB()
{
static B b(x, *this);
return b;
}
...

文件 b.cpp:

#include "b.h"
#include "a.h"
B::B(X &x, A &a) : x(x), a(a){}
void B::methodThatRequiresA(){
//does its thing...
}

在它们之外,我这样使用它们:

#include "x.h"
#include "a.h"
X x(...);
A a(x);
a.getB().methodThatRequiresA();

继续,我有一个类 B,它需要一个类 A 的对象才能工作,并且 A 通过 getB() 提供了一个使用自身的类型 B 的对象,因为每个 A 必须只有一个 B 的实例,我虽然这没关系。自从我这样做以来,编译时间增加了几秒钟,而且我的项目中只有一个非常小的类。

循环依赖需要这么长时间来编译吗?如果是这样,编译具有大量此类循环依赖项的项目可能会耗费大量时间。

最佳答案

编译大项目,尤其是优化可能需要相当长的时间。但在你的情况下,罪魁祸首是你没有在你的头文件中使用守卫,编译器必须多次解析同一个头文件。所以解决方案可能是(对于文件 a.h):

#ifndef A_H_
#define A_H_
//
//

#endif // A_H_

对此有不同的解决方案,例如来自 MS VS 等的 pragma once,但这是 IMO 最便携的方式。 Symbol 不必完全像这样,但必须是唯一的。

关于c++ - 循环依赖通常会花费很多时间来编译吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15042792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com