|
-
February 26th, 2003, 03:01 AM
#1
namespace
What is empty namespace for?
namespace
{
class A
{
.......
......
};
class B
{
......
.....
}
};
-
February 26th, 2003, 03:54 AM
#2
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.
Code:
namespace
{
class A
{
};
}
To be able to use the grouped members of an unnamed namespace there exists an implicit 'using' directive. The former example is equivalent to
Code:
namespace $$$
{
class A
{
};
}
using namespace $$$;
'$$$' 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.
-
February 26th, 2003, 04:59 AM
#3
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.
Code:
/* oldstyle.c */
static int local_global;
static void local_function();
/*------------- */
// newstyle.cpp
namespace
{
int local_global;
void local_function();
}
// -----------------
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.
When using C++, prefer unnamed namespace to static declaration.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|