I can’t find a good explanation about global non static variables in unnamed namespace. I avoid global variables as much as I can. In this particular case I’m interested about behaviour just from pure theoretic side.
Suppose the following code:
In a.h
namespace ai {
class Widget {
void DoSomething(int param);
};
}
In a.cc
namespace {
int x;
void Helper() {
}
}
namespace ai {
void Widget::DoSomething(int param) {
x = param;
Helper();
}
}
-
If I would create two instances
of the same class Widget, will both
instances share the same variable x? -
Is above behaviour the same if
class instances are on the same
thread vs different threads? -
What if the variable x would be
custom type instead of built-in
type? -
When variable x will be contructed and when destructed?
-
Is any relation between sizeof(Widget) and such variables?
-
What aspects are defined in C++ standard and what not?
Any other considerations, e.g. “need to know” about that topic? Maybe anyone could provide good book reference (e.g. “Effective C++..”) to read more?
x.x.x.It is exactly the same as if you had defined it as
static: Global inside the file, but hidden outside of it.Unnamed namespaces were added specifically to eliminate that particulay usage of
static(which has too many different meanings/usages)