The dis/advantage of forward declaration

时间:2023-03-08 21:50:38
The dis/advantage of forward declaration

In our projects, in C++ head file, if reference to some classes (reference or pointer), instead of include header file directly, we recommend to use forward declaration. Obviously, it can take some advantage to you.

  • Reduce the compile time
  • Avoid namespace pollution
  • Save unnecessary recompile (maybe it is a disadvantage)

But there are disadvantage (from google C++ style), so google guideline is “Avoid using forward declarations where possible. Just #include the headers you need.” Who is right? I don’t know but we did not meet any problem until now.

I copy the google guidelinebelow.

Avoid using forward declarations where possible. Just #include the headers you need.

A "forward declaration" is a declaration of a class, function, or template without an associated definition.

  • Forward declarations can save compile time, as #includes force the compiler to open more files and process more input.
  • Forward declarations can save on unnecessary recompilation. #includes can force your code to be recompiled more often, due to unrelated changes in the header.
  • Forward declarations can hide a dependency, allowing user code to skip necessary recompilation when headers change.
  • A forward declaration may be broken by subsequent changes to the library. Forward declarations of functions and templates can prevent the header owners from making otherwise-compatible changes to their APIs, such as widening a parameter type, adding a template parameter with a default value, or migrating to a new namespace.
  • Forward declaring symbols from namespace std:: yields undefined behavior.
  • It can be difficult to determine whether a forward declaration or a full #include is needed. Replacing an #include with a forward declaration can silently change the meaning of code:
      // b.h:

      struct B {};

      struct D : B {};

      // good_user.cc:

      #include "b.h"

      void f(B*);

      void f(void*);

      void test(D* x) { f(x); }  // calls f(B*)

If the #include was replaced with forward decls for B and D, test() would call f(void*).

  • Forward declaring multiple symbols from a header can be more verbose than simply #includeing the header.
  • Structuring code to enable forward declarations (e.g. using pointer members instead of object members) can make the code slower and more complex.
  • Try to avoid forward declarations of entities defined in another project.
  • When using a function declared in a header file, always #include that header.
  • When using a class template, prefer to #include its header file.