Unnamed namespaces

Unnamed namespaces

The unnamed-namespace-definition is a namespace definition of the form

 
inline(optional) namespace attr(optional) { namespace-body }    
 
attr(C++17) -   optional sequence of any number of attributes

This definition is treated as a definition of a namespace with unique name and a using-directive in the current scope that nominates this unnamed namespace.

namespace {
    int i;  // defines ::(unique)::i
}
void f() {
    i++;  // increments ::(unique)::i
}
 
namespace A {
    namespace {
        int i; // A::(unique)::i
        int j; // A::(unique)::j
    }
    void g() { i++; } // A::unique::i++
}
 
using namespace A; // introduces all names from A into global namespace
void h() {
    i++;    // error: ::(unique)::i and ::A::(unique)::i are both in scope
    A::i++; // ok, increments ::A::(unique)::i
    j++;    // ok, increments ::A::(unique)::j
}

Even though names in an unnamed namespace may be declared with external linkage, they are never accessible from other translation units because their namespace name is unique.

(until C++11)

Unnamed namespaces as well as all namespaces declared directly or indirectly within an unnamed namespace have internal linkage, which means that any name that is declared within an unnamed namespace has internal linkage.

(since C++11)
原文地址:https://www.cnblogs.com/zoneofmine/p/6408596.html