未命名的命名空间与全局声明 [英] Unnamed namespace Vs Global declaration

查看:69
本文介绍了未命名的命名空间与全局声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用未命名的名称空间和全局声明有什么区别?
使用这两种方法有什么具体的背景吗?
我们可以访问外部源文件中未命名的名称空间组件吗?

解决方案

未命名名称空间的目的是在翻译单元(=源文件)中提供唯一的名称空间,而无需显式前缀.这样可以保证您的全局名称不会与其他翻译单元中的其他相等的全局名称冲突.

例如:

 //file1.cpp命名空间{无效foo(){/* ... */}}#include"bar.h"int do_stuff(){foo();酒吧();返回5;} 

 //file2.cpp命名空间{无效foo(){/* ... */}}#include"bar.h"int do_something else(){酒吧();foo();返回12;} 

您可以将这两个翻译单元链接在一起,并确定两个名称 foo 将引用相应文件中定义的函数,并且您没有违反一定义规则./p>

从技术上讲,您可以将未命名的命名空间想像成这样:

 命名空间unique_and_unknowable_name{//...}使用名称空间unique_and_unknowable_name; 

没有此工具,您可以保证不违反ODR的唯一方法是使用 static 声明.但是,存在细微的差异,因为 static 影响链接,而名称空间则不影响.

What is the difference in using unnamed namespace and global declaration?
Is there any specific context for using these two?
Can we access unnamed namespace components in external source files?

解决方案

The point of an unnamed namespace is to provide a unique namespace within a translation unit (= a source file) without requiring an explicit prefix. This allows you to guarantee that your global names won't clash with other, equal global names in other translation units.

For example:

// file1.cpp

namespace
{
    void foo() { /* ... */ }
}

#include "bar.h"

int do_stuff()
{
    foo();
    bar();
    return 5;
}

// file2.cpp

namespace
{
    void foo() { /* ... */ }
}

#include "bar.h"

int do_something else()
{
    bar();
    foo();
    return 12;
}

You can link those two translation units together and know for certain that the two names foo will refer to the function defined in the respective file, and you do not violate the one-definition rule.

Technically, you can think of an unnamed namespace as something like this:

namespace unique_and_unknowable_name
{
    // ...
}

using namespace unique_and_unknowable_name;

Without this tool, the only way you could guarantee a non-violation of ODR would be to use static declarations. However, there's a subtle difference, in that static affects linkage, while namespaces do not.

这篇关于未命名的命名空间与全局声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆