This is the mail archive of the gdb@sources.redhat.com mailing list for the GDB project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: C++ namespace using directives


Jim Blandy <jimb@redhat.com> writes:

| Could a C++ person check my understanding of `using namespace'
| directives?
| 
| I'm reading Stroustrup, and the more I read about `using namespace',
| the weirder it gets.

:-)


|  Check this out:
| 
|     namespace A
|     {
|       int x;
|       int y;
|       int z;
|     };
| 
|     void f ()
|     {
|       int *x;
| 
|       {
|         int *y;
|         using namespace A;
| 
|         *x;  /* `x' refers to local x, not A::x */
|         *y;  /* `y` refers to local y, not A::y */
|         z;  /* `z' refers to A::z */ 
|       }
|     }
| 
| This program is type-correct, so you can see exactly which definitions
| those identifiers refer to.  I ran it through the newest GCC, and it
| didn't complain about ambiguities.  Stroustrup C.10.1 agrees.

Yes.  That matches the standard requirement:
3.4.1/2

  The declarations from the namespace nominated by a using-directive
  become visible in a namespace enclosing the using-directive; see
  7.3.4. For the purpose of the unqualified name lookup rules
  described in 3.4.1, the declarations from the namespace nominated by
  the using-directive are considered members of that enclosing namespace.

So in the above program, after the 'using namespace A', A::x and A::y
are considered (for the name lookup process) as members of the global
namespace.  So they are hidden by the local definitions in f().

| Weird, huh?  Although the `using namespace' directive does make A's
| variables visible, A's bindings are still *shadowed* by local
| variables in blocks that *enclose* the one containing the `using
| namespace' directive.

Exact.

| So, here's the way I'd describe the effect of a `using namespace'
| directive:
| 
| To look up some identifier X in a scope that has a `using namespace N'
| directive, search for both X and N::X.

In the transitive closure of the enclosing namespace.

[...]

| Regarding what constitutes an "ambiguity": if the same declaration
| makes it into a scope under two different names, that's not considered
| an ambiguity.

Right.

[...]

| However, if we give namespace B its own `int x' definition, the
| compiler does complain.

Right,

| Is this all correct?

Yes.

-- Gaby


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]