Masked Man
Masked Man

Reputation: 11075

What is the benefit of using ::namespace::something over namespace::something?

The code at my new workplace accesses namespaces using a seemingly redundant scope resolution at the start. For example, ::std::vector<int> instead of std::vector<int>.[1] I have never seen namespace access being done this way before.

One somewhat contrived scenario I could think of is when some namespace ns declares a nested namespace std, which too has a vector (in this example). Then the "additional" :: at the left ensures that the global std::vector is being used, not the local one. However, this is unlikely to be the reason given that our code goes through a rather elaborate review process making it almost impossible for anyone to introduce a new std namespace.

Are there any other scenarios where this could make a difference?


[1] I asked a few senior developers in the team to explain this to me, but they only have a vague idea why this "convention" is being used. The earliest developers who wrote the code left the team years ago, and nobody asked them about it before they left.

Upvotes: 1

Views: 563

Answers (1)

cadaniluk
cadaniluk

Reputation: 15229

The most notable scenario I can imagine is when using std::tolower and iterating over a container:

#include <cctype>
#include <algorithm>

std::string str = "Masked Man";
std::transform(str.begin(), str.end(), str.begin(), ::tolower);

As explained in this answer by @MatthieuM., it is a name clash between the tolower functions from <locale> and <cctype>. Since, on your implementation (it's actually unspecified), the C standard library functions perpetuated in the C++ standard library are in the std and the global namespace, ::tolower explicitly uses the one from <cctype>.

So, explicitly accessing the C standard library part of the C++ standard library counts as another reason, IMO.

Upvotes: 2

Related Questions