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
externkeyword withxin unnamed namespace?
Most of your questions are answered here. For the rest:
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.
No. In order to
externsomething, 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 toexternit, 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.