why prepend namespace with ::, for example ::std::vector
I have seen production code such as
::std::vector<myclass> myvec;
I have no i开发者_如何学Pythondea what the prepending ::
mean however - and why is it used?
For an example see:
C++: Proper way to iterate over STL containers
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. .
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.
Taking an example -
int variable = 20 ;
void foo( int variable )
{
++variable; // accessing function scope variable
::variable = 40; // accessing global scope variable
}
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
.
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.
精彩评论