What is empty namespace for?
namespace
{
class A
{
.......
......
};
class B
{
......
.....
}
};
Printable View
What is empty namespace for?
namespace
{
class A
{
.......
......
};
class B
{
......
.....
}
};
Namespaces allow you to group a set of global classes, objects and/or functions under one name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
Sometimes you just want to group something within a namespace which should not known outside the local context. In these cases it would be useless to come up with a unique name, which might collide with another one. In this case you can use unnamed namespaces.
To be able to use the grouped members of an unnamed namespace there exists an implicit 'using' directive. The former example is equivalent toCode:namespace
{
class A
{
};
}
'$$$' is a different name in every scope an unnamed namespace is declared. In addition unnamed namespaces are different for each translation unit. Therefore there is no possibility to access members from an unnamed namespaces from different translation units.Code:namespace $$$
{
class A
{
};
}
using namespace $$$;
Basically, and unnamed namespace serves the same purpose as declaring static objects at file scope: it keeps them local to the file and unusable outside it.
In both cases, "local_global" and "local_function" are available for use within the file (technically, "translation unit") that they are declared in, but not outside of it.Code:/* oldstyle.c */
static int local_global;
static void local_function();
/*------------- */
// newstyle.cpp
namespace
{
int local_global;
void local_function();
}
// -----------------
When using C++, prefer unnamed namespace to static declaration.