tags:

views:

738

answers:

1

I am working on some code written by a co-worker who no longer works with the company, and I have found the following code: (which I have cut down below)

namespace NsA { namespace NsB { namespace NsC {

    namespace { 
     class A { /*etc*/ };
     class B { /*etc*/ };
    }    

    namespace {
     class C { /*etc*/ };
    }
} } }

I don't understand the purpose of the namespace commands on lines 3 and 8.
Can someone explain what the purpose of an namespace entry with no name is?
Thanks

+29  A: 

That's an "anonymous namespace" - which creates a hidden namespace name that is guaranteed to be unique per "translation unit" (i.e. per CPP file).

This effectively means that all items inside that namespace are hidden from outside that compilation unit. They can only be used in that same file. See also this article on unnamed namespaces.

MadKeithV
Interesting. I didn't know you could do that. I'll have to keep it in mind.
Herms
It also obscolesces the need of `static` variables (compilation unit visibility)
xtofl
static is still useful occasionally. it will make the names not have extern linkage, while anonymous namespaces will name change the linkage of the names.
Johannes Schaub - litb
Hm, I thought unnamed namespaces forced internal linkage, but just looked it up, looks like you're right. Fancy that... :)
jalf
@GregRogers: Yes linkage matters, templates can only be instantiated with objects of external linkage (e.g. try declaring a class inside a function and using it inside vector< >, won't work, class in unnamed namespace outside function: will work...)
Pieter
Thanks for that last addition Pieter - something I had never considered. Good info!
MadKeithV