What's the <iosfwd>
header used for? Why is it necessary?
Any example?
It's so you can declare, in your own headers, methods that rely on the declarations of iostream types without having to #include
the iostream headers themselves, which are large, complex and slow to compile against.
Here's a simple example:
// foo.h
#include <iosfwd>
void sucker(std::iostream& is);
// foo.cc
#include <iostream>
void sucker(std::iostream& is) {
is >> somevar;
}
As @Marcelo Cantos mentioned, it's so you can include the declaration of iostream classes and functions without including the full definitions. In C and C++, a declaration is a statement that says "here is the name of something (a function/class/etc.), but I'm not going to tell you anything more about it besides its name". For a function, that means the name of the function, but not the body containing the function's code. For a class, that means the name of the class but not any of the class's member variables or methods.
Conversely, a definition is the full definition: the function body, the class members, etc.
Oftentimes you only need the declaration of something to use—in the case of a function, you don't need to know what the function's body looks like in order to call it (except in the case of templated or inlined functions). Likewise, with a class, you don't need to know what members the class has if all you're doing is passing around pointers or references to instances of that class. But as soon as you need to access a member variable or call a class method, then you do need the full definition.
By only including the declarations instead of the definitions, the total amount of code that the compiler has to process is much, much less, and hence compilation will proceed much more quickly.
To give you an idea of how much code is being processed, here's how much code is contained in my local implementation:
# The following commands create a source file that includes a single header
# file (on stdout), preprocess it with g++ -E, and then count how many lines
# are in the resulting preprocessed output
$ echo '#include <iosfwd>' | g++ -E -xc++ - | wc
2598 6534 57875
$ echo '#include <iostream>' | g++ -E -xc++ - | wc
25631 59613 631998
A file that includes <iosfwd>
, the compiler has to process 2598 lines of code from various header files, whereas a file that includes <iostream>
has to process a whopping 25631 lines of code. That's before compiling the actual code you care about in your source file!
Basically when you use <iosfwd>
is because you want to eliminate compile-time Dependencies.
You use <iosfwd>
instead of the traditional stream headers ( <iostream>
and friends ) so that you can avoid including the definition of the whole streaming stuff. With <iosfwd>
you are only making a forward declaration of all the streaming stuff.
I found this link particulary useful: http://www.gotw.ca/gotw/007.htm
精彩评论