c++c++11gccheader-files

Why don't I need to include STL headers in gcc 4.6?


I'm using gcc 4.6 in c++0x mode. I've noticed I don't seem to get any compiler errors if I use vectors and other STL containers but don't include their associated header files. Was this by design? What's the preferred practice?

I do always use explicitly specify the std namespace... but I always thought that the header had to be included even if the namespace is specified.

This seems like a strange default if it's preferable to include the headers since it's doubtful that I'll get things right 100% of the time without help from the compiler.


Solution

  • You should always include all the standard headers that your code needs.

    Unfortunately, standard headers are allowed to include other standard headers, in which case you may find yourself able to use something without including the correct header. You can't rely on that, and you may find that you have to fix your includes if you change to a different library implementation.

    There's no simple way to ensure you always get your includes correct; the easiest option is to test that your code compiles with all the library implementations you're interested in.