Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad practice to declare names in the standard namespace?

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 classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file."

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

like image 772
steve Avatar asked Apr 16 '11 01:04

steve


1 Answers

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 <iostream>

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 <iostream>. Your foo might then be a better match than the Standard Library implementation's foo.

like image 95
James McNellis Avatar answered Oct 22 '22 06:10

James McNellis