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.
a::m_a
. Instead it refers always to the
less nested. Is it always the case? What rules C++ is following?m_a
variable
from main()
?. 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;
}
Unnamed NamespacesThey are directly usable in the same program and are used for declaring unique identifiers. In unnamed namespaces, name of the namespace in not mentioned in the declaration of namespace. The name of the namespace is uniquely generated by the compiler.
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.
A Namespace is a set of unique names. Namespace is a mechanisms by which element and attribute name can be assigned to a group. The Namespace is identified by URI(Uniform Resource Identifiers).
You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time. However, this does not mean you cannot use the two namespace in the same program. You can use them each at different times in the same program.
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:
For a namespace X and name m, the namespace-qualified lookup set S(X,m) is defined as follows: Let S0(X,m) be the set of all declarations of m in X and the inline namespace set of X (7.3.1). If S0(X,m) is not empty, S(X,m) is S0(X,m); otherwise, S(X,m) is the union of S(Ni,m) for all namespaces Ni nominated by using-directives in X and its inline namespace set.
Now, remember that unnamed namespace is a uniquely named namespace with a using directive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With