在静态上使用未命名的名称空间 [英] Use of Unnamed namespace over static

查看:91
本文介绍了在静态上使用未命名的名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以假定在未命名的命名空间中声明的对象等同于static吗?

Can I assume an object declared in unnamed namespace to be equivalent to as if were static?

namespace { int x; };//  #1

static int x; // #2

FWIK,在两种情况下,x将具有静态存储持续时间和内部链接.
那么,声明为static的对象的所有规则是否适用于未命名命名空间中的对象?

FWIK, In both cases, x will have static storage duration and internal linkage.
So does all the rules of an object declared as static applies to an object in unnamed namespace?

例如:

  • 构造和破坏的顺序是什么?会一样吗?
  • 我可以在未命名的命名空间中将extern关键字与x一起使用吗?
  • What will be the order of construction and destruction? will it be same?
  • Can I use extern keyword with x in unnamed namespace?

推荐答案

构造和破坏的顺序是什么?会一样吗?

What will be the order of construction and destruction? will it be same?

该顺序与常规全局变量相同.因此它与静态不一样.

The order is unchanged from regular globals. So it isn't the same as static.

话虽这么说,我强烈敦促您编写不关心顺序的代码.您对全局变量依赖的初始化顺序越少越好.

That being said, I strongly urge you to write code that does not care about the order. The less you rely on the specific order of initialization for any globals, the better.

我可以在未命名的命名空间中将extern关键字与x一起使用吗?

Can I use extern keyword with x in unnamed namespace?

不.为了extern,必须输入其名称.而且,未命名空间的神奇之处在于您不能键入其名称.该名称由编译器分配.你不知道因此,如果您尝试extern它,则将替代其他功能.

No. In order to extern something, you have to be able to type its name. And the magic of the unnamed namespace is that you can't type its name. The name is assigned by the compiler. You don't know it. So if you attempt to extern it, you will instead be externing something else.

如果将未命名的名称空间放在标头中,则包含该名称空间的每个翻译单元都将获得该变量的不同版本.他们都是extern,但是他们将谈论不同外部变量.

If you put an unnamed namespace in a header, every translation unit that includes it will get a different version of the variable. They'll all be extern, but they'll be talking about a different external variable.

这篇关于在静态上使用未命名的名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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