Why is adding names to the std
namespace undefined behaviour?
The obvious answer is "because the standard says so," e.g. in C++14 [namespace.std] 17.6.4.2.1/1:
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace
std
or to a namespace within namespacestd
unless otherwise specified. ...
However, I would be really interested in the reasons for this ruling. I can of course understand adding overloads of names already in std
could break behaviour; but why is adding new, unrelated names a problem?
Programs can already wreak havoc inside std
with macros, which is why pretty much all standard library implementations have to consist solely of reserved names (double-underscore and starting-underscore-followed-by-capital) for all non-public parts.
I would really be interested in a situation in which something like this can be problematic:
namespace std
{
int foo(int i)
{ return i * 42; }
}
#include <algorithm> // or one or more other standard library headers
when this is perfectly legal and the standard library has to cope:
#define foo %%
#include <algorithm> // or one or more other standard library headers
What is the rationale for this Undefined Behaviour?
While this practice is okay for example code, pulling in the entire std namespace into the global namespace is not good as it defeats the purpose of namespaces and can lead to name collisions. This situation is called namespace pollution.
Need of namespace: As the same name can't be given to multiple variables, functions, classes, etc. in the same scope. So to overcome this situation namespace is introduced.
It doesn't affect the runtime performance at all.
Thus, removing using namespace std; changes the meaning of those unqualified names, rather than just making the code fail to compile. These might be names from your code; or perhaps they are C library functions.
Here are a few reasons:
::std::foo(int)
as part of its implementation it would be a violation of the one definition rule.std
any name added to the standard C++ library would be a likely breaking change. To some extent this is already true in the sense that any such name could be a macro but it is considered acceptable to break those.std
: they can be added to arbitrary other namespace, i.e., even if the motivations given above are not particular strong, the restriction isn't considered to matter in any form. ...and if there is a reason to add a name to namespace std
, it clearly does affect the behavior.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