views:

1080

answers:

5

Someone asserted on SO today that you should never use anonymous namespaces in header files. Normally this is correct, but I seem to remember once someone told me that one of the standard libraries uses anonymous namespaces in header files to perform some sort of initialization.

Am I remembering correctly? Can someone fill in the details?

+2  A: 

See this discussion: http://stackoverflow.com/questions/357404/anonynous-namespaces

John D. Cook
that's the thread where he has got that information from that anonymous namespaces in headers is bad
Johannes Schaub - litb
A: 

I really can see no positive benefit from using anonymous namespaces in headers. The confusion that can result from having the same symbol declaration mean, in essence, a different thing in the compilation units that include that header would be a guaranteed way to go prematurely and painfully bald.

Jon Trauntvein
A: 

If it's initialization, it would likely be an iostreams header (like istream, ios, etc.).

Max Lybbert
+2  A: 

I don't see any point in putting an anonymous namespace into a header file. I've grepped the standard and the libstdc++ headers, found no anonymous namespaces apart of one in the tuple header (C++1x stuff):

  // A class (and instance) which can be used in 'tie' when an element
  // of a tuple is not required
  struct _Swallow_assign
  {
    template<class _Tp>
      _Swallow_assign&
      operator=(const _Tp&)
      { return *this; }
  };

  // TODO: Put this in some kind of shared file.
  namespace
  {
    _Swallow_assign ignore;
  }; // anonymous namespace

This is so you can do

std::tie(a, std::ignore, b) = some_tuple;

elements of the some_tuple are assigned the variables at the left side (see here), a similar technique is used for this iterator. The second element is ignored.

But as they say, it should be put into a .cpp file and the one instance should be shared by all users. They would put a declaration of it into the header like this then:

extern _Swallow_assign ignore;
Johannes Schaub - litb
C++1x? Did I miss something?
Adam Mitz
next c++ version
Johannes Schaub - litb
Sutter is still calling it C++0x (http://herbsutter.wordpress.com/2008/10/28/september-2008-iso-c-standards-meeting-the-draft-has-landed-and-a-new-convener/).
Adam Mitz
wait.. now i understand why he called me pessimist :) well litb and some other pessimists call it c++1x. let's see who's going to win the bet :p
Johannes Schaub - litb
+3  A: 

The only situation in which a nameless namespace in header can be useful is when you want to distribute code as header files only. For example, a large standalone subset of Boost is purely headers.

The token ignore for tuples, mentioned in another answer is one example, the _1, _2 etc. bind placeholders are others.

James Hopkin
i think you have made a good point with this.
Johannes Schaub - litb