文章目录
  1. 为什么要用anonymous namespace?

6.15 — Unnamed and inline namespaces

This might make unnamed namespaces seem useless. But the other effect of unnamed namespaces is that all identifiers inside an unnamed namespace are treated as if they had internal linkage, which means that the content of an unnamed namespace can’t be seen outside of the file in which the unnamed namespace is defined.

For functions, this is effectively the same as defining all functions in the unnamed namespace as static functions. The following program is effectively identical to the one above:


匿名命名空间和关键词 static 都可以让其声明的变量或函数变为内部链接属性,那么它们之间的区别是什么?

回答
首先,匿名命名空间比关键词 static 的功能更丰富,因此我们更推荐使用前者。比如,static 无法修饰类(class/struct),

// 非法代码
static class sample_class { /* class body / };
static struct sample_struct { /
struct body */ };

// 合法代码
namespace
{
class sample_class { /* class body */ };
struct s
}

文章目录