I tried this dummy code below to test unnamed namespace.
I have the following output
ctor 1
ctor 0
3
5
I am a bit confused about this.
- I was expecting an error from the compiler saying that it cannot resolve
an ambiguity regardinga::m_a. Instead it refers always to the
less nested. Is it always the case? What rules C++ is following? - It seems that the compiler creates variable CMyObj following the order
written on the file. Is this always the case? - is there any way to access the most nested
m_avariable
frommain()?.
class CMyObj{
public:
CMyObj(int a){std::cout << "ctor " << a << std::endl; }
};
namespace a{
namespace{
int m_a=4;
int m_b=5;
CMyObj m_obj(1);
}
}
namespace a{
int m_a=3;
CMyObj m_obj(0);
}
int main(){
std::cout << a::m_a << std::endl; // which one?
std::cout << a::m_b << std::endl; // how this is possible?
return 0;
}
I don’t have C++03 standard with me to check the wording there, so I will quote from FDIS n3290. I think the answer to this question is found in qualified name lookup rules in 3.4.3.2/2:
Now, remember that unnamed namespace is a uniquely named namespace with a using directive.