Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why prepend namespace with ::, for example ::std::vector

Tags:

c++

namespaces

I have seen production code such as

::std::vector<myclass> myvec;

I have no idea what the prepending :: mean however - and why is it used?

For an example see:

C++: Proper way to iterate over STL containers

like image 874
Tom Avatar asked Feb 07 '11 19:02

Tom


3 Answers

This fully qualifies the name, so that only the vector template in the std namespace in the global namespace is used. It basically means:

{global namespace}::std::vector<myclass> myvec;

There can be a difference when you have entities with the same name in different namespaces. For a simple example of when this could matter, consider:

#include <vector>

namespace ns
{
    namespace std
    {
        template <typename T> class vector { };
    }

    void f() 
    { 
        std::vector<int> v1;   // refers to our vector defined above
        ::std::vector<int> v2; // refers to the vector in the Standard Library
    }        
};

Since you aren't allowed to define your own entities in the std namespace, it is guaranteed that ::std::vector will always refer to the Standard Library container. std::vector could possibly refer to something else. .

like image 56
James McNellis Avatar answered Nov 16 '22 02:11

James McNellis


The leading "::" refers to the global namespace. Suppose you say namespace foo { .... Then std::Bar refers to foo::std::Bar, while ::std::Bar refers to std::Bar, which is probably what the user meant. So always including the initial "::" can protect you against referring to the wrong namespace, if you're not sure which namespace you're currently in.

like image 31
Kerrek SB Avatar answered Nov 16 '22 02:11

Kerrek SB


Taking an example -

int variable = 20 ;

void foo( int variable )
{

    ++variable;      // accessing function scope variable
    ::variable = 40;  // accessing global scope variable
}
like image 4
Mahesh Avatar answered Nov 16 '22 04:11

Mahesh