Visual Studio C++ 编译器奇怪的行为

Visual Studio C++ compiler weird behaviour

我只是想知道为什么这段代码在 Visual Studio 中可以正确编译(并且没有警告)。也许结果与GCC and Clang相同,但不幸的是我现在无法测试它们。

struct T {
    int t;
    T() : t(0) {}
};

int main() {
    T(i_do_not_exist);
    return 0;
}

T(i_do_not_exist);是对象声明,与T i_do_not_exist;.

意义相同

N4567 § 6.8[stmt.ambig]p1

There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion (5.2.3) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration.

§ 8.3[dcl.meaning]p6

In a declaration T D where D has the form

( D1 )

the type of the contained declarator-id is the same as that of the contained declarator-id in the declaration

T D1

Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.

因为它定义了一个T类型的变量:

http://coliru.stacked-crooked.com/a/d420870b1a6490d7

#include <iostream>

struct T {
    int t;
    T() : t(0) {}
};

int main() {
    T(i_do_not_exist);
    i_do_not_exist.t = 120;
    std::cout << i_do_not_exist.t;
    return 0;
}

上面的例子看起来很傻,但这种语法是有原因的。

一个更好的例子是:

int func1();
namespace A
{
   void func1(int);
   struct X {
       friend int (::func1)();
   };
}

可能还能找到其他示例。