Why add a namespace with :: e.g. :: std :: vector

I saw production code like

::std::vector<myclass> myvec; 

I have no idea what the preliminary :: - means and why is it used?

Example:

C ++: the right way to iterate over STL containers

+6
c ++ namespaces
source share
5 answers

The leading "::" refers to the global namespace. Suppose you say namespace foo { ... Then std::Bar refers to foo::std::Bar , and ::std::Bar refers to std::Bar , which probably matters to the user. Therefore, always including the initial "::" can protect you from accessing the wrong namespace if you are not sure which namespace you are currently located.

+3
source share

This is fully consistent with the name, so only the vector template in the std in the global namespace is used. This basically means:

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

There may be a difference when you have objects with the same name in different namespaces. For a simple example, when this may make a difference, 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 are not allowed to define your own entities in the std , it is guaranteed that ::std::vector will always refer to the standard library container. std::vector may refer to something else.,

+17
source share

It always takes vector from the standard library. std::vector can also be mycompany::std::vector if the code in which I use it is in the mycompany namespace.

+3
source share

Taking an example -

 int variable = 20 ; void foo( int variable ) { ++variable; // accessing function scope variable ::variable = 40; // accessing global scope variable } 
+3
source share

Starting with :: means reset the namespace to the global namespace. This can be useful if you are trying to deal with some ambiguity in your code.

+1
source share

All Articles