Visual Studio C++ compiler weird behaviour

不想你离开。 提交于 2019-12-02 21:47:25

T(i_do_not_exist); is an object declaration with the same meaning as 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.

marcinj

Because it defines a variable of type 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;
}

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.

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