Reputation: 17557
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:
extern
keyword with x
in unnamed namespace? Upvotes: 8
Views: 1256
Reputation: 506847
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.
Upvotes: 2
Reputation: 473222
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.
Upvotes: 8