C++ 匿名namespace的作用以及它与static的区别

一、匿名namespace的作用
在C语言中,如果我们在多个tu(translation unit)中使用了同一个名字做为函数名或者全局变量名,则在链接阶段就会发生重定义错误,为了解决这个问题,我们可以在定义这些标识符(identifier)的时候加上static关键字修饰以限制它只在一个tu范围内可见。
C++继承了C语言中static关键字的这个用途,我们依旧可以使用static来避免多个tu中使用同一个标识符带来的重定义问题。此外C++还提供了另一种特有的方式,那就是匿名namespace:一个没有指定名字的namespace被称为一个匿名namespace;在一个tu中可以出现多个匿名namespace,并且相同层次的匿名namespace实际上被合成为同一个;出现在不同tu的匿名namespace中的相同标识符相互独立不会发生冲突,因此我们可以把那些只希望在同一个tu范围可见的全局标识符放入一个匿名namespace中,效果与前面加static相同。

二、匿名namespace与static的区别
一个全局标识符被static修饰后它的linkage变为internal linkage,这就是为什么不同tu中的相同标识符不会发生冲突的原因。
而匿名namespace却并不会改变在它内部定义的标识符的linkage,它用来避免名字冲突所采用的手段同C++用来实现重载的手段一摸一样,就是使用名字改编(name mangling):根据C++标准7.3.1.1,每个tu中的匿名namespace实际上会拥有一个独一无二的名字,因此在不同tu的匿名namespace中相同的标识符实际上属于不同的namespace,自然在名字改编后就不会发生冲突了:

7.3.1.1 Unnamed namespaces [namespace.unnamed]
An unnamed-namespace-definition behaves as if it were replaced by
        namespace unique { /* empty body */ }
        using namespace unique;
        namespace unique { namespace-body }
where all occurrences of unique in a translation unit are replaced
by the same identifier and this identifier differs from all other
identifiers in the entire program.

为什么匿名namespace不采取跟static一样的做法呢,搞个新花样岂不是增加了编译器开发的负担?这其实是因为另一个C++的特性牵制了匿名namespace的实现,那就是模板非类型参数(template non-type arguments):

14.3.2 Template non-type arguments [temp.arg.nontype]
A template-argument for a non-type, non-template template-parameter
shall be one of:
— an integral constant-expression of integral or enumeration type; or
— the name of a non-type template-parameter; or
— the address of an object or function with external linkage, including
   function templates and function template-ids but excluding non-static
   class members, expressed as & id-expression where the & is optional
   if the name refers to a function or array, or if the corresponding
   template-parameter is a reference; or
— a pointer to member expressed as described in 5.3.1 .

正是被红字标出的external linkage这一需求限制了匿名namespace的实现!试想一下,假如我们有一个全局对象或者函数只希望它在一个tu中有效,又希望能够用它的地址来实例化一个模板,怎么办?只在一个tu中有效,可以选择internal linkage,但是要用它的地址做为模板参数,又要求它必须要是external linkage!!
很显然,匿名namespace不改变其内部标识符的linkage这一性质解决了这一难题,我们可以把这个全局对象或者函数放心的扔在一个匿名namespace中,然后用它的地址来实例化一个模板,绝对不会发生重定义错误:)

现在大部分C++书籍都认为匿名namespace和static是相同的,而正如这里所阐述的,它们之间差异是明显的:static修饰的标识符由于internal linkage的限制,是不能用来实例化模板的!

最后给出一个例子证实匿名namespace确实不改变linkage,呵呵
代码中验证了external linkage/internal linkage/no linkage三种情况
-------------------------------------------------------------------------------

1template <char *p> 2struct foo 3{ 4    void bar(); 5}; 6static char a ='a'; 7namespace 8{ 9    char b = 'b'; 10    static char c = 'c'; 11    template <class T> struct xxx {}; 12    void foobar() 13    { 14        struct no_linkage {}; 15        xxx<no_linkage>();  // 如果编译错误,说明no_linkage的linkage没有变化 16    } 17} 18int main() 19{ 20    foo<&a>().bar();  // 由于a的linkage是internal,因此应该编译错误 21    foo<&b>().bar();  // 如果编译正确,说明b的linkage是external 22    foo<&c>().bar();  // 如果编译错误,说明c的linkage是internal 23    foobar(); 24    return 0; 25}

-------------------------------------------------------------------------------
Comeau C/C++ 4.3.3 (Aug  6 2003 15:13:37) for ONLINE_EVALUATION_BETA1
Copyright 1988-2003 Comeau Computing.  All rights reserved.
MODE:strict errors C++

"ComeauTest.c", line 19: error: a template argument may not reference a
          local type
      xxx<no_linkage>();
          ^
          ^

"ComeauTest.c", line 25: error: a template argument may not reference a
          non-external entity
          Hint: http://www.comeaucomputing.com/techtalk/templates/#stringliteral
    foo<&a>().bar();
        ^

"ComeauTest.c", line 27: error: a template argument may not reference a
          non-external entity
          Hint: http://www.comeaucomputing.com/techtalk/templates/#stringliteral
    foo<&c>().bar();
        ^

3 errors detected in the compilation of "ComeauTest.c".

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

FLV文件格式

1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  

C++ 匿名namespace的作用以及它与static的区别 - HelloWorld