1

I know in C++, we use :: to qualify the namespace for a variable or function, like myNamespace::a. But I notice some usages like ::myFunction(). Does it mean the function belongs to the global namespace?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
hackjutsu
  • 8,336
  • 13
  • 47
  • 87
  • This just ensures that resolution occurs in the global namespace instead of the namespace you are in. See http://stackoverflow.com/questions/4269034/what-is-the-meaning-of-prepended-double-colon – larrylampco Jul 27 '16 at 18:26

2 Answers2

3

If the code compiles, then yes, ::myFunction() is referencing the global declaration of myFunction.

This is most commonly used when a local definition shadows your global definition:

namespace local {
    int myFunction() {}; // local namespace definition
};
int myFunction() {}; // global definition.
using namespace local;

int main() {
    // myFunction(); // ambiguous two definitions of myFunction in current scope.
    local::myFunction(); // uses local::myFunction();
    ::myFunction(); // uses global myfunction();
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
3

Yes, it means the variable, type or function following it must be available in the global namespace.

It can be used for example when something is shadowed by a local definition:

struct S {
  int i;
};

void f() {
  struct S {
    double d;
  };

  S a;
  ::S b;

  static_assert(sizeof(a) != sizeof(b), "should be different types");
}
Dutow
  • 5,638
  • 1
  • 30
  • 40
  • 1
    Take a look at [`type_traits`](http://en.cppreference.com/w/cpp/header/type_traits) and [`decltype`](http://en.cppreference.com/w/cpp/language/decltype) to get around types that have the same size. eg: `static_assert(std::is_same::value, "should be different types");` – user4581301 Jul 27 '16 at 19:05