I am reading some code snippets from others and I find a line:
using namespace::std;
I suspect its purpose is using namespace std;
, with some typos. But to my surprise the compiler accepts this code without any complaint. I build with:
$ g++ --version
g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
$ /usr/bin/g++ ${SRC} -std=c++11 -pthread -Wall -Wno-deprecated -o ${OUT}
I wonder why is this code valid, and what effects will it make? I suspect it is a bad practice.
It's equivalent to using namespace ::std;
and also equivalent to using namespace std;
. The ::
refers to the global namespace, and std
is put in the global namespace indeed.
As the syntax of using-directives:
(emphasis mine)
attr(optional) using namespace nested-name-specifier(optional) namespace-name ;
... ...
nested-name-specifier - a sequence of names and scope resolution operators ::, ending with a scope resolution operator. A single :: refers to the global namespace.
... ...
using namespace::std
is the same as using namespace std;
The ::
symbol is the scope resolution operator. When used without a scope name before it , it refers to the global namespace. This means that std
is a top level namespace, and is not enclosed in another.
The spaces before and after the ::
are optional in this case because the lexer can deduce the tokens from the context.
For example, all of the following are valid:
namespace A { namespace notstd{} } // define my own namespaces A and A::notstd
using namespace::std; // the standard library std
using namespace A;
using namespace ::A;
using namespace::A;
using namespace A::notstd;
Update:
As noted in one of the comments, using namespace ::std;
and using namespace std;
may actually lead to different results if the statement comes inside another namespace which contains its own nested namespace std
. See the following (highly unlikely) example:
#include <stdio.h>
namespace A {
namespace std {
int cout = 5;
}
using namespace std;
void f1() {
cout++;
}
}
int main()
{
A::f1();
printf("%d\n",A::std::cout); // prints 6
return 0;
}
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