c++ - VS2012 不编译此代码,但 G++、clang 和 ICC 都在没有诊断的情况下接受它

标签 c++ visual-studio-2012

基于 this answer , 我想出了 this code对于 C++ 中的常量树结构:

#include <tuple>
struct T
{
    T(const char* n, const T& n1, const T& n2, const T& n3, const T& n4):
        name(n), nodes(n1, n2, n3, n4) {}

    const char* name;
    std::tuple<const T&, const T&, const T&, const T&> nodes;
};

T n(0, n, n, n, n);

GCC(4.5.3 和最新版本)、ICC (17) 和 CLang(3.5 和最新版本)都编译此代码(CLang 3.5 发出 -Wuninitialized 警告,但是没关系,因为 n 是一个占位符,其值无关紧要。

然而,MSVC 11 (VS2012) 在 n 的定义上出现 C2065 错误:

test6.cpp(12) : error C2065: 'n' : undeclared identifier

什么给了? MSVC 是否拒绝有效代码?我是不是在 UB-land,恶魔从我的 Nose 里飞出来?如果这无效,有人可以告诉我标准中的哪些内容使其无效和/或为什么 GCC、Clang 和 ICC 都接受它?

最佳答案

将其简化为一个简单的

unsigned char x(x);

并在 http://webcompiler.cloudapp.net/ 上在线测试显示当前版本的 Microsoft 编译器仍然拒绝它。

这是一个编译器错误。引用标准(N4140,大致为 C++14,但规则与早期标准相同):

3.3.2 Point of declaration [basic.scope.pdecl]

1 The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [Example:

unsigned char x = 12;
{ unsigned char x = x; }

Here the second x is initialized with its own (indeterminate) value. -- end example ]

= x;(x); 在语法上都是 initializer,在 (x); 语法,变量 x 不知何故还不在范围内。

Visual Studio 的编译器接受 = x; 语法。

但由于它只影响在其自身初始化中使用变量的代码,因此更好地重新编写代码可以完全避免该问题。

关于c++ - VS2012 不编译此代码,但 G++、clang 和 ICC 都在没有诊断的情况下接受它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42119710/

相关文章:

c# - 调试符号未加载

c++ - 从 C++ 中的字符串中删除字符

c# - 使用语句不起作用 - VS 2012

asp.net-mvc-3 - 向 MVC3 添加 View 时的异常

c++ - boost::interprocess 互斥锁崩溃而不是等待锁?

html - CSS中的 `lightgrey`和 `lightgray`有什么区别?

visual-studio - Visual Studio 2012 文档下载

c++ - 跨线程函数调用修改变量

C++ 日历问题

c++ - 为什么 void{} 不存在?