Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef inside/outside anonymous namespace?

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;
}
like image 339
Jay Avatar asked Dec 05 '09 14:12

Jay


2 Answers

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.

like image 55
Timo Geusch Avatar answered Oct 08 '22 04:10

Timo Geusch


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.

like image 40
Thomas Avatar answered Oct 08 '22 05:10

Thomas