得之我幸 失之我命

when someone abandons you,it is him that gets loss because he lost someone who truly loves him but you just lost one who doesn’t love you.

匿名 namespace

1
2
3
4
namespce
{
char c;
}

这是啥?命名空间的名字呢?这个 c 要怎么在其他地方调用?

当定义一个命名空间时,可以忽略这个命名空间的名称,成为一个匿名命名空间,并且编译器在内部会为这个命名空间生成一个唯一的名字,而且还会为这个匿名的命名空间生成一条 using 指令

所以上面的代码在效果上等同于:

1
2
3
4
5
namespace __UNIQUE_NAME_
{
char c;
}
using namespace __UNIQUE_NAME_;

在匿名命名空间中声明的名称也将被编译器转换,与编译器为这个匿名命名空间生成的唯一内部名称(即这里的 _UNIQUE_NAME)绑定在一起

还有一点很重要,在匿名命名空间中声明的名称具有 internal 链接属性,这和声明为 static 的全局名称的链接属性是相同的,即名称的作用域被限制在当前文件中,无法通过在另外的文件中使用 extern 声明来进行链接

注意:命名空间都是具有 external 连接属性的,只是匿名的命名空间产生的 __UNIQUE_NAME_ 在别的文件中无法得到,因为这个唯一的名字是不可见的

C++ 新的标准中提倡使用匿名命名空间,而不推荐使用 static,因为 static 用在不同的地方涵义不同,容易造成混淆;另外,static 不能修饰 class

一个问题:In the Google C++ Style Guide, the Namespaces section states that “Use of unnamed namespaces in header files can easily cause violations of the C++ One Definition Rule (ODR).”

Including that header file in any source file will case ODR violation, since is defined twice. This occurs because an unnamed namespace is given a unique identifer by the compiler, and all occurrences of an unnamed namespace in a translation unit are given the same identifier. To paraphrase: every TU has at most one unnamed namespace.c

be slow to promise and quick to perform.