Tom
Tom

Reputation: 5309

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

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

Upvotes: 13

Views: 4499

Answers (5)

James McNellis
James McNellis

Reputation: 355267

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

Upvotes: 23

Mahesh
Mahesh

Reputation: 34625

Taking an example -

int variable = 20 ;

void foo( int variable )
{

    ++variable;      // accessing function scope variable
    ::variable = 40;  // accessing global scope variable
}

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 477494

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.

Upvotes: 6

Maister
Maister

Reputation: 5054

Starting with :: means to reset the namespace to global namespace. It might be useful if you're trying to fight some ambiguity in your code.

Upvotes: 2

Oswald
Oswald

Reputation: 31685

This always takes the vector from the standard library. std::vector might as well be mycompany::std::vector if the code where I use it is in namespace mycompany.

Upvotes: 3

Related Questions