“using namespace” in c++ headers

后端 未结 9 2194
失恋的感觉
失恋的感觉 2020-11-22 01:32

In all our c++ courses, all the teachers always put using namespace std; right after the #includes in their .h files. This seems to me

相关标签:
9条回答
  • 2020-11-22 02:06

    You need to be careful when including headers inside of headers. In large projects, it can create a very tangled dependency chain that triggers larger/longer rebuilds than were actually necessary. Check out this article and its follow-up to learn more about the importance of good physical structure in C++ projects.

    You should only include headers inside a header when absolutely needed (whenever the full definition of a class is needed), and use forward declaration wherever you can (when the class is required is a pointer or a reference).

    As for namespaces, I tend to use the explicit namespace scoping in my header files, and only put a using namespace in my cpp files.

    0 讨论(0)
  • 2020-11-22 02:07

    Like all things in programming, pragmatism should win over dogmatism, IMO.

    So long as you make the decision project-wide ("Our project uses STL extensively, and we don't want to have to prepend everything with std::."), I don't see the problem with it. The only thing you're risking is name collisions, after all, and with the ubiquity of STL it's unlikely to be a problem.

    On the other hand, if it was a decision by one developer in a single (non-private) header-file, I can see how it would generate confusion among the team and should be avoided.

    0 讨论(0)
  • 2020-11-22 02:14

    Check out the Goddard Space Flight Center coding standards (for C and C++). That turns out to be a bit harder than it used to be - see the updated answers to the SO questions:

    • Should I use #include in headers
    • Self-sufficient headers in C and C++

    The GSFC C++ coding standard says:

    §3.3.7 Each header file shall #include the files it needs to compile, rather than forcing users to #include the needed files. #includes shall be limited to what the header needs; other #includes should be placed in the source file.

    The first of the cross-referenced questions now includes a quote from the GSFC C coding standard, and the rationale, but the substance ends up being the same.

    0 讨论(0)
提交回复
热议问题