8

Can I assume an object declared in unnamed namespace to be equivalent to as if were static?

namespace { int x; };//  #1

static int x; // #2

FWIK, In both cases, x will have static storage duration and internal linkage.
So does all the rules of an object declared as static applies to an object in unnamed namespace?

For example:

  • What will be the order of construction and destruction? will it be same?
  • Can I use extern keyword with x in unnamed namespace?
cpx
  • 17,009
  • 20
  • 87
  • 142

2 Answers2

8

Most of your questions are answered here. For the rest:

What will be the order of construction and destruction? will it be same?

The order is unchanged from regular globals. So it isn't the same as static.

That being said, I strongly urge you to write code that does not care about the order. The less you rely on the specific order of initialization for any globals, the better.

Can I use extern keyword with x in unnamed namespace?

No. In order to extern something, you have to be able to type its name. And the magic of the unnamed namespace is that you can't type its name. The name is assigned by the compiler. You don't know it. So if you attempt to extern it, you will instead be externing something else.

If you put an unnamed namespace in a header, every translation unit that includes it will get a different version of the variable. They'll all be extern, but they'll be talking about a different external variable.

Community
  • 1
  • 1
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    Could you expand on the difference between a global (externalizable) variable and a file-static variable when it comes to the order of construction and destruction ? I thought (perhaps naively) that it was the same. – Matthieu M. Nov 23 '11 at 07:27
  • @MatthieuM.: If I recall correctly, file-static variables are all initialized before globals. I could be wrong though. Which is yet another reason to not rely on it. – Nicol Bolas Nov 23 '11 at 08:07
  • 1
    @NicolBolas: I think you are confusing file-static with the zeroing of memory. Indeed initialization of globals happen in two phases. In a first phase, built-ins (and structs with no constructors) are initialized from *constants* and the rest (which require function execution) is zeroed; in a second phase, the functions are executed (including constructors). This is what guarantees that you can test a global pointer for nullity and set it on first (real) use. – Matthieu M. Nov 23 '11 at 09:22
2

Both have internal linkage (the one in the unnamed namespace only in c++11) but the one in the unnamed namespace is not a member of the global namespace. so for example you can put an x into the unnamed namespace and the global namespace and they will not conflict.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212