Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does putting a structure in an anonymous namespace do? [duplicate]

Possible Duplicate:
Why are unnamed namespaces used and what are their benefits?

Looking at someones code and this is what they have declared:

namespace {

  struct myStruct {
     int x;
     int y;
  } obj1;

}

..in a function I see it used like this:

myStruct& var = obj1;

(Notice namespace is anonymous.)

From how I see it used, I can not figure out why it is declared and used like this.

What does declaring it like this do differently?

Also, why is the pointer created like this rather than the traditional style shown here. i.e. myStruct *ptr;

Thank You!

like image 955
T.T.T. Avatar asked Dec 04 '22 14:12

T.T.T.


1 Answers

Everything that's declared inside an anonymous namespace gets a unique, unknowable name, and thus cannot be referred to from any other translation unit. The anonymous namespace is thus guaranteed to be local to the current translation unit only, and never to clash with a different one.

For example, if you say namespace { int i; }, you are guaranteed that only the current translation unit sees the global i. Even if this declaration is in a header that's included in multiple, different TUs, each TU receives its own copy of the global variable (each with a different, unknowable fully-qualified name).

The effect was similar to declaring a global object static (which gives the global object internal linkage) in C++03, where objects in the anonymous namespace may still have external linkage. In C++11, names in an unnamed namespace have internal linkage as per 3.5/4, so the effect is exactly the same for variables and functions as declaring them static – but internal linkage applies to more than just variables and functions (e.g. enums, classes, templates), so as of C++11, you should always prefer unnamed namespaces!

like image 58
Kerrek SB Avatar answered Dec 09 '22 15:12

Kerrek SB