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?
std
might have undocumented things in it, that might interact with things that you'd put instd
yourself (for example, you might be defining something with a name that already exists, and then the standard can't guarantee that everything works as specified anymore). – Sheikhstd
with with an undocumentedstd::x
" cope with me doing#define x %%%
? – Pretoriusvector::random_iterator
, you add it tostd
, and in the next version the wise people who make these decisions think: "Hey, let's add avector::random_iterator
" and makearray_shuffle
use it. – Sanburnstd
namespace is to standardize things, so allowing you to change it would rather defeat the point. – Unshackle#define
or#undef
names declared in any standard library header"? (C++11, 17.6.4.3.1). (It's not limited to documented names.) – Gaur