Bad practice to declare names in the standard namespace?

前端 未结 5 708
轻奢々
轻奢々 2021-01-18 02:15

I was looking through the Google C++ style guide, and came across this:

\"Do not declare anything in namespace std, not even forward declarations of standard library

5条回答
  •  情歌与酒
    2021-01-18 03:11

    Could someone explain what this means and why this is undefined behavior using example code?

    The following program yields undefined behavior:

    namespace std {
        void foo(int) { }
    }
    
    #include 
    
    int main() {
        std::cout << "Hello World!" << std::endl;
    }
    

    Why? It declares a function named foo in namespace std. As for why this could cause a problem, consider: the Standard Library implementation might have its own function named foo() and that might be used by some component in . Your foo might then be a better match than the Standard Library implementation's foo.

提交回复
热议问题