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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With