开发者

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::So开发者_高级运维meClass;
  typedef SomeClass::Buffer MyBuf;
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜