What is the difference between spelling ":: namespace :: identifier" and "namespace :: identifier"?

I have seen both approaches in code. Could you explain what is the difference between the two? I think this is due to the way namespace searches are done using C ++, can you provide some information about this, or maybe a link to a good document? Thanks.

+4
source share
2 answers

This is not a big deal, at least in most cases.

In the format ::identifier1::identifier2 previous colon says to look at the global area for identifier1 , and then look for identifier2 in that area.

In the format identifier1::identifier2 instead we look at the current area for identifier1 . If we do not find it, there will be a search for the parent's object, and so on, until we find it. Then we look for identifier2 within the area that we just found.

In the event that you are already in the global scope, it does not matter. But this story changes when you work in a namespace or classes that have other namespaces or classes.

+5
source

Example:

 #include <cstdio> namespace x { const int i = 1; } namespace y { namespace x { const int i = 2; } void func() { std::printf("x::i = %d\n", x::i); std::printf("::x::i = %d\n", ::x::i); } } int main() { y::func(); return 0; } 

Output:

  x :: i = 2
 :: x :: i = 1

Explanation:

  • When you reference an identifier of type x::i , the definition used is the β€œclosest” x::i . Inside ::y::func definition ::y::x::i closer than the definition ::x::i . On the contrary, there is no such function ::y::std::printf , so ::std::printf used instead.

  • When you refer to an identifier like ::x::i , there is no ambiguity: it searches for a top-level namespace with the name x , and then finds i inside.

Thus, using :: at the beginning, you can write the full name of the global. It also allows you to distinguish between local and global variables.

Example 2:

 #include <cstdio> const int x = 5; int main() { const int x = 7; std::printf("x = %d\n", x); std::printf("::x = %d\n", ::x); return 0; } 

Output:

  x = 7
 :: x = 5
+12
source

Source: https://habr.com/ru/post/1383258/


All Articles