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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With