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 namespace std
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…