在匿名命名空间中放置结构有什么作用? [英] What does putting a structure in an anonymous namespace do?

查看:140
本文介绍了在匿名命名空间中放置结构有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


查看someones代码,这是他们已经声明的:

  namespace {

struct myStruct {
int x;
int y;
} obj1;

}

..在一个函数中我看到它像这样使用:

  myStruct& var = obj1; 

(注意命名空间是匿名的。 / p>

从我如何看待它,我不知道为什么这样声明和使用。



这样声明它的方式不同吗?



此外,为什么是这样创建的指针而不是传统风格此处显示。即myStruct * ptr;



谢谢!

解决方案

在匿名命名空间中声明的内容获得唯一的,不可知的名称,因此不能从任何其他翻译单元引用。因此,保证匿名命名空间只对当前翻译单元是本地的,并且不会与不同的翻译单元冲突。



例如,如果你说 namespace {int i; } ,您保证只有当前翻译单元看到全局 i 。即使此声明位于包含在多个不同TU中的标头中,每个TU也会收到其拥有的全局变量(每个都有不同的,不可知的完全限定名称)的副本。



效果类似于在C ++ 03中声明一个全局对象 static (它提供了全局对象内部链接),其中匿名命名空间中的对象可能仍然具有外部链接。在C ++ 11中,未命名的命名空间中的名称具有内部链接,如3.5 / 4,所以效果是完全相同的变量和函数,如声明它们 static –但内部链接不仅适用于变量和函数(例如枚举,类,模板),因此对于C ++ 11,你应该总是喜欢未命名的命名空间!


Possible Duplicate:
Why are unnamed namespaces used and what are their benefits?

Looking at someones code and this is what they have declared:

namespace {

  struct myStruct {
     int x;
     int y;
  } obj1;

}

..in a function I see it used like this:

myStruct& var = obj1;

(Notice namespace is anonymous.)

From how I see it used, I can not figure out why it is declared and used like this.

What does declaring it like this do differently?

Also, why is the pointer created like this rather than the traditional style shown here. i.e. myStruct *ptr;

Thank You!

解决方案

Everything that's declared inside an anonymous namespace gets a unique, unknowable name, and thus cannot be referred to from any other translation unit. The anonymous namespace is thus guaranteed to be local to the current translation unit only, and never to clash with a different one.

For example, if you say namespace { int i; }, you are guaranteed that only the current translation unit sees the global i. Even if this declaration is in a header that's included in multiple, different TUs, each TU receives its own copy of the global variable (each with a different, unknowable fully-qualified name).

The effect was similar to declaring a global object static (which gives the global object internal linkage) in C++03, where objects in the anonymous namespace may still have external linkage. In C++11, names in an unnamed namespace have internal linkage as per 3.5/4, so the effect is exactly the same for variables and functions as declaring them static – but internal linkage applies to more than just variables and functions (e.g. enums, classes, templates), so as of C++11, you should always prefer unnamed namespaces!

这篇关于在匿名命名空间中放置结构有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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