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.
CodePudding user response:
It's just same as using namespace ::std;
, then has the same effect with using namespace std;
in fact. 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.
... ...
CodePudding user response:
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;