Is static deprecated when ensuring availability between translation units?

旧时模样 提交于 2020-01-04 01:38:10

问题


From the following stackoverflow answer, the user says:

It means that the variable is local to a translation unit (simply put, to a single source file), and cannot be accessed from outside it. This use of static is in fact deprecated in the current C++ Standard - instead you are supposed to use anonymous namespaces:

static int x = 0;

should be:

namespace {
    int x = 0;    
}

I don't disagree that anonymous namespaces are the preferred method,
but is using static really deprecated now?
Where does the standard say this?


回答1:


No, it is not currently deprecated. It was at one point but this was reversed due to C comparability issues. At some point before 1999 it was deprecated and this lead to defect report 174 which says:

The decision to deprecate global static should be reversed.

  • We cannot deprecate static because it is an important part of C and to abandon it would make C++ unnecessarily incompatible with C.
  • Because templates may be instantiated on members of unnamed namespaces, some compilation systems may place such symbols in the global linker space, which could place a significant burden on the linker. Without static, programmers have no mechanism to avoid the burden.

This lead to defect report 223 in which the meaning of deprecation was revised from:

deprecated is defined as: Normative for the current edition of the Standard, but not guaranteed to be part of the Standard in future revisions.

it was noted that this implies, only non-deprecated features will be support in future standards:

However, this definition would appear to say that any non-deprecated feature is "guaranteed to be part of the Standard in future revisions." It's not clear that that implication was intended, so this definition may need to be amended.

and changed the meaning of deprecated to:

These are deprecated features, where deprecated is defined as: Normative for the current edition of the Standard, but having been identified as a candidate for removal from future revisions.

and later the feature was undeprecated due to C compatibility issues by defect report 1012:

Although 7.3.1.1 [namespace.unnamed] states that the use of the static keyword for declaring variables in namespace scope is deprecated because the unnamed namespace provides a superior alternative, it is unlikely that the feature will be removed at any point in the foreseeable future, especially in light of C compatibility concerns. The Committee should consider removing the deprecation.



来源:https://stackoverflow.com/questions/34139882/is-static-deprecated-when-ensuring-availability-between-translation-units

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!