Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of the c++ using directive

From section 7.3.4.2 of the c++11 standard:

A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified name lookup (3.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace. [ Note: In this context, “contains” means “contains directly or indirectly”. —end note ]

What do the second and third sentences mean exactly? Please give example.

Here is the code I am attempting to understand:

namespace A
{
    int i = 7;
}
namespace B
{
    using namespace A;
    int i = i + 11;
}
int main(int argc, char * argv[])
{
    std::cout << A::i << " " << B::i << std::endl;
    return 0;
}

It print "7 7" and not "7 18" as I would expect.

Sorry for the typo, the program actually prints "7 11".

like image 273
ThomasMcLeod Avatar asked Sep 20 '12 16:09

ThomasMcLeod


1 Answers

The using statement in your code is irrelevant. B::i is already in scope when the initializer for B::i is evaluated. You can trivially prove this by deleting the using statement; your code should compile and run just the same. In any case, the value of B::i ends up being undefined because it depends on an uninitialized value (i.e. the value that B::i had when the initializer was evaluated).

like image 66
Lily Ballard Avatar answered Sep 25 '22 00:09

Lily Ballard