views:

225

answers:

2

In a .cpp file, is there any difference/preference either way?

// file scope outside any namespace
using X::SomeClass;
typedef SomeClass::Buffer MyBuf;

v/s

namespace { // anonymous
  using X::SomeClass;
  typedef SomeClass::Buffer MyBuf;
}
+3  A: 

There is not much point in placing typedefs in anonymous namespaces. The main use for anonymous namespaces is to avoid symbol collision between translation units by placing definitions with external linkage in them.

Thomas
Hmm I thought the anonymous namespace had scope over the whole file contents, including other namespaces in the file, which would make it identical to putting things in file scope anyway (except for external linkage rules). I wasnt sure if external linkage rules would be relevant to syntactic sugar like typedefs and using.
Jay
You are right, placing the using declaration in the anonymous namespace or not does not change anything. I was mistaken. I have edited this out.
Thomas
+2  A: 

I would say that the second usage is rather uncommon, at least in the code that I've seen so far (and I've seen quite a lot C++ of code). Could you explain what the reasoning behind the second technique is?

You will normally use an anonymous namespace in a C++ implementation file to achieve the same thing that 'static' would do in C (or C++, but we'll gloss over that), namely restricting the visibility of the symbols to the current translation unit. The typedef doesn't actually produce symbols that are exported for the linker to see as they don't create anything 'concrete' in the sense of anything concrete that you could link against.

My recommendation? I'd go with the first notation. The second one adds an unnecessary complication and in my opinion, doesn't buy you anything.

Timo Geusch
Speaking of that using namespace {} instead of static seems like an hack to me, and I never liked or used it. If they were worried about the 9 million different uses of static they should have introduced a new keyword..
Andreas Bonini
Strangely enough, I do prefer the anonymous namespace instead of static, even though I've done my fair share of C programming. It is precisely the 9 million uses and counting of static that makes me use anonymous namespaces. Plus, I find it a little more concise and it's harder to screw up compared to forgetting to prefix something with 'static'.
Timo Geusch
I used to have a bunch of debug stuff in the anonymous namespace which is now gone. The only useful thing left is the typedefs and using, so I was debating whether to move them to file scope and junk the anonymous namespace.
Jay
If that's the whole contents I would move it into file scope unless there is a danger of breaking something (if you've got SomeClass in multiple namespaces, for example). It would make the code cleaner IMHO and remove some of the say what? moments when you go back to it in six months time.
Timo Geusch