简体   繁体   中英

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM