[英]Visual Studio C++ compiler weird behaviour
I'm just curious to know why this small piece of code compiles correctly (and without warnings) in Visual Studio . 我只是想知道为什么这小段代码在Visual Studio中正确编译(并且没有警告)。 Maybe the result is the same with GCC and Clang , but unfortunately I can't test them now.
也许结果与GCC和Clang相同,但不幸的是我现在无法测试它们。
struct T {
int t;
T() : t(0) {}
};
int main() {
T(i_do_not_exist);
return 0;
}
T(i_do_not_exist);
is an object declaration with the same meaning as T i_do_not_exist;
是一个对象声明,其含义与
T i_do_not_exist;
相同T i_do_not_exist;
. 。
N4567 § 6.8[stmt.ambig]p1 N4567§6.8[stmt.ambig] p1
There is an ambiguity in the grammar involving expression-statement s and declaration s: 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 .语法中涉及表达式语句和声明 s存在歧义:具有函数式显式类型转换的表达式语句 (5.2.3),因为其最左侧的子表达式与第一个声明符以a开头的声明无法区分。
(
。在这些情况下,该声明是一个声明 。
§ 8.3[dcl.meaning]p6 §8.3[dcl.meaning] p6
In a declaration
TD
whereD
has the form在
TD
的声明中,D
表格
( D1 )
the type of the contained declarator-id is the same as that of the contained declarator-id in the declaration
所包含的说明符-ID的类型是相同的,在声明的说明符包含-ID的
T D1
Parentheses do not alter the type of the embedded declarator-id , but they can alter the binding of complex declarators.
括号不会改变嵌入式声明符id的类型,但它们可以改变复杂声明符的绑定。
Because it defines a variable of type T: 因为它定义了T类型的变量:
http://coliru.stacked-crooked.com/a/d420870b1a6490d7 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;
}
The above example looks silly, but this syntax is allowed for a reason. 上面的例子看起来很愚蠢,但允许这种语法是有原因的。
A better example is: 一个更好的例子是:
int func1();
namespace A
{
void func1(int);
struct X {
friend int (::func1)();
};
}
Probably other examples could be found. 可能还有其他例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.