Superiority of unnamed namespace over static?

Nawaz picture Nawaz · Dec 12, 2010 · Viewed 38.3k times · Source

How are unnamed namespaces superior to the static keyword?

Answer

Nawaz picture Nawaz · Dec 12, 2010

You're basically referring to the section §7.3.1.1/2 from the C++03 Standard,

The use of the static keyword is deprecated when declaring objects in a namespace scope; the unnamed-namespace provides a superior alternative.

Note that this paragraph was already removed in C++11. static functions are per standard no longer deprecated!

Nonetheless, unnamed namespace's are superior to the static keyword, primarily because the keyword static applies only to the variables declarations and functions, not to the user-defined types.

The following code is valid in C++:

//legal code
static int sample_function() { /* function body */ }
static int sample_variable;

But this code is NOT valid:

//illegal code
static class sample_class { /* class body */ };
static struct sample_struct { /* struct body */ };

So the solution is, unnamed (aka anonymous) namespace, which is this:

//legal code
namespace 
{  
     class sample_class { /* class body */ };
     struct sample_struct { /* struct body */ };
}

Hope it explains that why unnamed namespace is superior to static.

Also, note that use of static keyword is deprecated when declaring objects in a namespace scope (as per the Standard).