Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "using namespace::std" in C++

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.

like image 585
rustyhu Avatar asked Dec 22 '22 14:12

rustyhu


2 Answers

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.
... ...

like image 66
songyuanyao Avatar answered Jan 01 '23 22:01

songyuanyao


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;
}
like image 41
Gonen I Avatar answered Jan 01 '23 22:01

Gonen I