I am reading Herb Sutter's More Exceptional C++
and item 37 on forward declarations says:
Never
#include
a header when a forward declaration will suffice. Prefer to#include
only<iosfwd>
when the complete definition of a stream is not needed.
Also I heard plenty of advice on including only the headers needed by the compilation unit to reduce dependencies.
I understand perfectly well why this should apply to project headers, but I do not quite understand why is it bad to include unnecessary standard headers.
For example I do something like this:
//standard_library.h
#ifndef STANDARD_LIBRARY
#define STANDARD_LIBRARY
#include <iostream>
#include <chrono>
#include <thread>
...
// Everything I need in the project
#endif
and include this single header everywhere, where I need something from std
The problems that I can imagine are:
But I haven't had significant problems with 1. sofar. Almost everything is in the std namespace. Also I do not fully understand why 2. is necessarily a significant problem. The standard headers rarely change. Also as far as I know the compiler can precompile them. When it comes to templates, they are instantiated(compiled) only when I need them.
There are also benefits:
I am a beginner programer without experience on big projects and I sincerely want to figure this out so please have mercy upon me.
Besides
you named "Less figuring out which headers I need and in which header a certain function is" as a benefit. I agree so far as this can be true for well designed libraries and headers.
In practice however I experienced (at least with MFC/ATL) some errors which could be solved by figuring out the correct order of includes. On the other hand one day you want to resolve an issue which makes you travel across the included headers - now imagine yourself looking at tons of headerfiles actually having nothing to do with your code file.
My conclusion is: The time you save by including a bunch of unnecessary headers do not pay off if you have to maintain a large project later on. The more time you invest before starting including any headers, the more time you will safe afterwards - but mostly without actually recognizing it.