“using namespace” in c++ headers

后端 未结 9 2176
失恋的感觉
失恋的感觉 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 01:57

    Item 59 in Sutter and Alexandrescu's "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices":

    59. Don’t write namespace usings in a header file or before an #include.

    Namespace usings are for your convenience, not for you to inflict on others: Never write a using declaration or a using directive before an #include directive.

    Corollary: In header files, don't write namespace-level using directives or using declarations; instead, explicitly namespace-qualify all names.

    A header file is a guest in one or more source files. A header file that includes using directives and declarations brings its rowdy buddies over too.

    A using declaration brings in one buddy. A using directive brings in all the buddies in the namespace. Your teachers' use of using namespace std; is a using directive.

    More seriously, we have namespaces to avoid name clash. A header file is intended to provide an interface. Most headers are agnostic of what code may include them, now or in the future. Adding using statements for internal convenience within the header foists those convenient names on all the potential clients of that header. That can lead to name clash. And it's just plain rude.

提交回复
热议问题