Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it appropriate to use static (over unnamed namespaces) in C++?

I have been reading articles about unnamed namespaces the whole day, most articles explained when you should use unnamed namespaces over the static keyword. But I am still left with one big question when is it appropriate to use static? After all it is not completely deprecated, what about header files with static functions should I put them into unnamed namespaces now?

#ifndef HEADER_H
#define HEADER_H

static int func() {
  ...
}

// versus:

namespace {
  int func() {
    ...
  }
};

#endif // HEADER_H 

Or what about static member functions?

Greetings

like image 301
haribo Avatar asked Oct 08 '10 14:10

haribo


2 Answers

The precise wording of the standard is:

The use of the static keyword is deprecated when declaring objects in namespace scope.

Functions in a header file should be inline rather than static or in an unnamed namespace. inline means you will only end up with at most one copy of the function in your program, while the other methods will give you a separate copy from each file that includes the header. As well as bloat, this could give incorrect behaviour if the function contains function-static data. (EDIT: unless the function is supposed to have different definitions in different compilation units, perhaps due to different preprocessor macros that are defined before including the header file. In that case the best approach is not to include it at all, but rather to bury it in an unmarked grave with a stake through its unholy heart.)

Data objects, apart from constants, usually shouldn't be defined in header files at all, only declared extern.

Static member functions are a different kettle of fish, and you have to use static there as there is no other way to declare them. That usage isn't deprecated, since it isn't in namespace scope.

UPDATE: C++11 has removed the deprecation, so there's no longer any particular reason to prefer unnamed namespaces over static. But you still shouldn't use either in a header file unless you're doing something weird.

like image 164
Mike Seymour Avatar answered Oct 05 '22 14:10

Mike Seymour


There is no advantage of static in namespace scope over unnamed namespaces which I know of. Use unnamed namespaces, as in the example above. Actually in the example above I can't see why is static or unnamed namespace necessary. Maybe inline? And static member functions have nothing to do with static at namespace scope. Static member functions (and nonfunction members) are still valid.

like image 22
Armen Tsirunyan Avatar answered Oct 05 '22 13:10

Armen Tsirunyan