匹配使用具体类型说明符的extern声明

匹配使用具体类型说明符的extern声明

本文介绍了是否使用“自动”匹配使用具体类型说明符的extern声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下程序:

extern int x;
auto x = 42;
int main() { }

Clang 3.5接受它(),GCC 4.9和VS2013不()。谁是正确的,C ++标准中指定的正确行为在哪里?

Clang 3.5 accepts it (live demo), GCC 4.9 and VS2013 do not (live demo for the former). Who is right, and where is the correct behavior specified in the C++ Standard?

推荐答案

关于我们听说有关重新声明的所有内容:

There's surprisingly little in the standard about this. About all we hear about redeclaration is:

c $ c>的语义:

and the only relevant part of auto's semantics:

(提醒我们 code>是 int )。

我们知道一个变量必须被赋予相同的类型声明:

We know that a variable must be given the same type by all declarations:

和所有类型调整应该小心有关 auto 参与所有这些的任何问题;我的解释是,这本质上是 x 在全局范围的有效重新声明(和定义),类型 int ,并且Clang是正确的。即使我们建议 auto 不算作类型调整,因为不需要诊断,在最坏情况下,所有列出的实现都符合自己的方式。

and the "after all adjustments of types" ought to take care of any questions regarding auto's participation in all of this; my interpretation, then, is that this is inherently a valid redeclaration (and definition) of the x at global scope with type int, and that Clang is correct. Even if we propose that auto does not count as "adjustment of type", since no diagnostic is required, at worst all listed implementations are compliant in their own way.

我相信GCC和Visual Studio正在采取以下作为灵感:

I believe GCC and Visual Studio are taking the following as inspiration:

…但我认为这是短视的。标准语言似乎不可能禁止通常的重新声明规则,只是因为它们不在 7.1.6.4 内重复或明确引用。

…but I think that this is short-sighted. It seems unlikely that the standard language is intended to prohibit the usual redeclaration rules, just because they are not repeated or explicitly referenced from within 7.1.6.4.

C ++ 14增加了与推导的类型的函数声明相关的措辞:

C++14 adds wording that relates to declarations of functions with deduced types:

通过对称,可能会建议在 int 的情况下,意味着GCC和VS在拒绝程序时是正确的。但是,这是一个不同的功能(因为扣除不能应用于纯粹的声明),因此不同的场景。

By symmetry one might suggest that, in your int case, it is intended that GCC and VS be correct in rejecting the program. However, this is a different feature (since deduction cannot be applied to mere declarations) and thus a different scenario.

无论如何,改进的标准措辞将有所帮助。我认为这是一个[相当小的]编辑缺陷。

Either way, improved standard wording would help here. I consider it a [reasonably minor] editorial defect.

这篇关于是否使用“自动”匹配使用具体类型说明符的extern声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:30