前瞻性声明的缺点是什么? [英] What are the drawbacks of forward declaration?

查看:137
本文介绍了前瞻性声明的缺点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果可能的话,在所有地方使用转发声明是否有任何缺点。这是如果我的头只包含声明。

I am wondering if there is any drawback for using forward declarations in all places when possible. This is if my header contains only declarations.

据我所知,使用forward声明加快了编译时间,但我不知道有什么缺点。

As far as I understand, using forward declaration speeds up compile time, but I don't know of any drawbacks as such.

p>

a.h:

Class A
{
};

bh: b
$ b

b.h:

// Should I use and include "a.h" in the cpp file (e.g., a.cpp)
Class A;
Class B
{
    doSomething(A *a);
    A *myA;
};

或者最好使用

bh:

b.h:

#include "a.h"

Class B
{
    doSomething(A *a);
    A *myA;
};


推荐答案

使用转发声明可改善 >。如果可以通过使用forward声明避免包含A.h,那么最好使用forward声明。它最好不仅是因为你的构建运行得更快(毕竟,预处理的头文件可以很好地处理编译器的效率),但因为它告诉读者你的声明你的类 B 不依赖于知道你的类 A 的任何东西,除了它存在 *

Using forward declarations improves decoupling. If you can avoid including "A.h" by using a forward declaration, it is a good idea to use forward declaration. It is better not only because your builds run faster (after all, preprocessed headers can deal with compiler efficiency pretty well) but because it tells the readers of your declaration that the structure of your class B does not depend on knowing anything about your class A, other than that it exists*.

EDIT (回答你的问题)我知道的转发声明的唯一缺点是你不能在所有情况下使用它们:例如,一个类似如下的声明:

EDIT (to answer your question) The only downside to forward declarations that I know is that you cannot use them in all situations: for example, a declaration similar to this:

class B
{
    A myA[10];
};

无法编译,因为编译器需要知道 A

would not compile, because the compiler needs to know the size of A. However, the compiler finds such issues very reliably, and informs you about them in unambiguous terms.

* 类<$ c $的实现方法c> B 很可能取决于知道类 A 的详细信息。但是,这个依赖关系变成了从你的类的用户隐藏的 B 的实现细节;你可以随时更改它,而不会破坏依赖于 B 类的代码。

* The implementation of class B could very well depend on knowing the details of class A. However, this dependency becomes an implementation detail of B hidden from the users of your class; you can change it at any time without breaking the code dependent upon class B.

这篇关于前瞻性声明的缺点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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