Is it well-formed, if I redefine a variable as auto, and the deduced type is the same? [duplicate]

前提是你 提交于 2019-11-28 03:18:01

问题


Look at this snippet:

int a;
extern int b;
auto b = a;

Is it well-formed? Clang successfully compiles it, but GCC and MSVC don't.

(This issue has come up when I answered How to declare and define a static member with deduced type?)


回答1:


Tl;DR;

clang is correct, the logic is that this is allowed by [dcl.spec.auto] and to restrict this for deduced return types [dcl.spec.auto]p11 was added otherwise there is no restriction and therefore this is not restricted for the variables case.

See my more complete answer in the duplicate




回答2:


Clang, GCC, MSVC. (This answer previous stated that all 3 compilers would refuse to build it, but that was incorrect.)

dcl.spec.auto does not address the compatibility of multiple declarations of the same variable when mixing the auto type specifier with other type specifiers. However, it addresses it for function return types:

auto f();
auto f() { return 42; } // return type is int
auto f();               // OK
int f();                // error, cannot be overloaded with auto f()
decltype(auto) f();     // error, auto and decltype(auto) don't match

So my intuition is that this is an oversight in the standard and the behavior is currently unspecified, but if/when it gets specified, there would be precedent to make it illegal. (On the other hand, variables can't be overloaded, so who knows.)



来源:https://stackoverflow.com/questions/52304410/is-it-well-formed-if-i-redefine-a-variable-as-auto-and-the-deduced-type-is-the

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