namespace over static

Started by
4 comments, last by TrueTom 18 years, 1 month ago
To limit the scope of external variable to a specific translation unit I always used static. But now I came to know a new thing that standard committee has deprecated the use of static keyword for such purpose. We should use namespace instead. Can anyone explain me why?
Advertisement
Anonymous namespaces can hold classes as well as variables.

Also, the static keyword doesn't make sense for translation unit specific variables now that it is also used for static member variables in C++.

[Edited by - Nitage on March 1, 2006 8:49:14 AM]
Quote:Original post by Nitage
Anonymous namespaces can hold classes and functions as well as variables.

Also, the static keyword doesn't make sense for translation unit specific variables now that it is also used for static member variables in C++.


Couldn't understood what you are trying to say ?
Old school C & C++ used to use the static keyword for many and varied things. One way of using it is to make names - variables, functions etc. - visible only within that one sourcefile (translation unit in standards speak). Because static has been abused and overloaded, it was felt that a better way should be found to "hide" information inside translation units. Namespaces were introduced to provide partitioning of code into units larger than one class or source file.
Now where a namespace is used without a name (is it just a space?) this is called an anonymous namespace and fulfills the function of your statics. So generally in more modern software you will see something like:

#include

// previously ...

// static int myStaticFunction ()
// {
// return 123;
// }


// anonymous...
namespace
{
// used exactly as before
int myStaticFunction ()
{
return 123;
}
}

// ... and our other code remains unchanged...


int MyClass::MyMethod ()
{
return myStaticFunction ();
}

HTH.

Quote:Original post by TEUTON
To limit the scope of external variable to a specific translation unit I always used static. But now I came to know a new thing that standard committee has deprecated the use of static keyword for such purpose.
We should use namespace instead.

Can anyone explain me why?


A namespace-level declaration has extern linkang by default, so it can be used in template instantiations. A name with static linkage cannot.

Names contained within namespace (other than the global namespace) can participate properly in overload resolution and Koenig lookup. A name with static linkage and in the global namespace will not be considered for those purposes, leading to bizarre and unexpected compile-time problems.

If you're sticking to C-with-classes, there is no advantage to using a namespace over using a static global.

Stephen M. Webb
Professional Free Software Developer

Fear my memory:

Link

This topic is closed to new replies.

Advertisement