Should '#include' and 'using' statements be repeated in both header and implementation files (C++)?

后端 未结 5 1547
無奈伤痛
無奈伤痛 2021-02-14 20:33

I\'m fairly new to C++, but my understanding is that a #include statement will essentially just dump the contents of the #included file into the location of that statement. This

5条回答
  •  你的背包
    2021-02-14 20:48

    • Only include in a header/source what you really need (if forward declarations are available, and enough, then forward declare instead of including)
    • Don't use using statement in headers (unless inside function scopes)... Adding using in the header will pollute the namespaces of all the sources including the header.
    • You should make sure each file (header of source) includes everything it needs, and nothing more.

    You don't need to care if some includes are redundant. Header guards and precompiler optimizations are there to handle that for you.

    You should be able to manipulate each file in isolation.

    For example, let's say you use the std::string in the header and in the source, but, as an "optimization", you only included the string in the header... If you discover later you don't need anymore the string in the header, and want to remove it (code cleaning, and all...), you will have to modify the source to include the string. Now, let's imagine you have TEN sources including the header...

    Now, of course, you can have exceptions to this rule (for example, precompiled headers, or even headers woe sole aim is to do multiple includes as a courtesy), but by default, you should have self-sufficient header and source files (i.e. files that include anything they use, no more no less).

提交回复
热议问题