Restrictions on Namespaces
The C++ Standard defines several restrictions on the use of namespaces. These restrictions are meant to avert anomalies or ambiguities that can create havoc in the language.
Namespace std Can Not Be Modified
Generally, namespaces are open, so it is perfectly legal to expand existing namespaces with additional declarations and definitions across several files. The only exception to the rule is namespace std. According to the standard, the result of modifying namespace std with additional declarations -- let alone the removal of existing ones -- yields undefined behavior, and is to be avoided. This restriction might seem arbitrary, but it's just common sense -- any attempt to tamper with namespace std undermines the very concept of a namespace dedicated exclusively to standard declarations.
User-Defined new and delete Cannot Be Declared in a Namespace
The Standard prohibits declarations of new and delete operators in a namespace. To see why, consider the following
example:
char *pc; //global
namespace A
{
void* operator new ( std::size_t );
void operator delete ( void * );
void func ()
{
pc = new char ( 'a'); //using A::new
}
} //A
void f() { delete pc; } // call A::delete or //::delete?
Some programmers might expect the operator A::delete to be selected because it matches the operator new that was used to allocate the torage; others might expect the standard operator delete to be called because A::delete is not visible in function f(). By prohibiting declarations of new and delete in a namespace altogether, C++ avoids any such ambiguities.
Partager