Re: Question about Unnamed Namespace
On Oct 15, 5:44 am, Neelesh Bodas <neelesh.bo...@gmail.com> wrote:
> On Oct 15, 8:15 am, CrazyJohn <gatesgates2...@gmail.com> wrote:
> > This is my first time posting question here, if I break any rules,
> > please kindly point out. And I'm really glad to be a part of this
> > community.
> > Here is my question,
> > Our lecturer told us that Unnamed Namespace is an alternative to
> > Static Internal Variables, but he also said that Namespace has an
> > "Open" nature. Then, what if we create an integer variable in an
> > unnamed namespace in one file and then create another integer variable
> > with the same name in the unnamed namespace in another file? Will this
> > cause a naming conflict?
> > -- file1.cpp --
> > namespace
> > {
> > int chenchen;
> > }
> > -- file2.cpp --
> > namespace
> > {
> > int chenchen;
> > }
> > If there is a naming conflict, then Unnamed Namespace is not able to
> > function exactly the same as Static Internal Variable does; If there
> > is no conflict, then Unnamed Namespace doesn't have an "Open"
> > nature......So, why the standard includes such a feature?.......
> > ( Sorry, I am new to C++, actually I don't even know what exactly I
> > should ask.....)
> The footnote to 7.3.1.1(1) of the C++ standard says: "Although
> entities in an unnamed namespace might have external linkage, they are
> effectively qualified by a name unique to their
> translation unit and therefore can never be seen from any other
> translation unit"
> What this means is that entities in an unnamed namespace are not
> visible from other TUs.
That's not quite true. What it means is that they cannot be
names in other TU's. If your compiler supports export, they can
be seen and used by template instantiations, when the template
has been defined in another TU. (That is, in fact, part of the
reason why the anonymous namespace was invented.)
Note for example:
template< int& ri > class T{} ;
static int i1 ;
T< i1 > t1 ; // Illegal...
namespace { int i2 ; } ;
T< i2 > t2 ; // Legal...
If T were actuallly exported, and contained code, that code
could refer to i2 by means of its argument ri. Even though the
code was in another translation unit. This is not possible with
static.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
|