0

In my current job, I am seeing variables declared in the unnamed namespace in the cpp file and used only by that class as if they are member variables.

I see it as an interesting way of keeping only interface information in .h and implmentation in .cpp and is less work than the usual pimpl idiom.

I see people using pimpl all the time but never this approach, is there any problem with it?

Lap
  • 244
  • 2
  • 9
  • 4
    Is the 'pimp' idiom the one where 'money==power'? – Aesthete Jul 20 '12 at 08:43
  • In old C you had to mark global variables and functions `static` to keep them local to the file and not being exported. In C++ you can instead use anonymous namespaces for the same effect. – Some programmer dude Jul 20 '12 at 08:45
  • 1
    Can you give an example of what you mean? You _can't_ declare members at namespace scope, you can only declare them in a class. If they're declared at namespace scope (unnamed or not) then they are not members. – Jonathan Wakely Jul 20 '12 at 08:45

2 Answers2

1

Variables declared in the unnamed namespace of a .cpp file are file scoped; this means that there is only one instance per execution of the program.

You can see this for yourself by creating two instances of your object and observing that they interfere with each other's variables in the unnamed namespace.

ecatmur
  • 137,771
  • 23
  • 263
  • 343
  • only `static` variables declared in the unnamed namespace of a .cpp file are file scoped. Otherwise they may have external linkage and be accesable from other files as well – Andrew Jul 20 '12 at 09:11
  • @Andrew non-`static` variables in the unnamed namespace might have external linkage, but they can't be accessed from other translation units: see http://stackoverflow.com/questions/4181059/linkage-of-symbols-within-anonymous-namespace-within-a-regular-namespace – ecatmur Jul 20 '12 at 09:26
-1

Show some example code please. AFAIK, you cannot declare member variables in the unnamed namespace (unless the class itself is declared in the unnamed namespace).

The unnamed namespace was introduced to replace the common practice of declaring variables as static that are used in just one compilation unit.

Axel
  • 13,204
  • 4
  • 44
  • 72
  • My bad, those variables are not member variables anymore, but used only by that class as if they are member variables. – Lap Jul 20 '12 at 09:16
  • 1
    They can't be used as member variables, as there's only one instance per class. However, they can be used as if they were static member variables – Tom Tanner Jul 20 '12 at 09:34