如果我将变量重新定义为 auto,并且推导的类型相同,它是否格式正确?
Is it well-formed, if I redefine a variable as auto, and the deduced type is the same?
看看这个片段:
int a;
extern int b;
auto b = a;
格式是否正确? Clang 成功编译它,但 GCC 和 MSVC 没有。
(我回答How to declare and define a static member with deduced type?时出现了这个问题)
Clang, GCC, MSVC。 (这个回答之前说所有 3 个编译器都会拒绝构建它,但这是不正确的。)
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
所以我的直觉是,这是标准中的疏忽,目前未指定行为,但 if/when 它被指定,会有先例使其非法。 (另一方面,变量不能重载,所以谁知道呢。)
Tl;DR;
clang 是正确的,逻辑是 [dcl.spec.auto]
允许并限制推导的 return 类型添加 [dcl.spec.auto]p11 否则没有限制,因此这是不受变量情况的限制。
见my more complete answer in the duplicate
看看这个片段:
int a;
extern int b;
auto b = a;
格式是否正确? Clang 成功编译它,但 GCC 和 MSVC 没有。
(我回答How to declare and define a static member with deduced type?时出现了这个问题)
Clang, GCC, MSVC。 (这个回答之前说所有 3 个编译器都会拒绝构建它,但这是不正确的。)
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
所以我的直觉是,这是标准中的疏忽,目前未指定行为,但 if/when 它被指定,会有先例使其非法。 (另一方面,变量不能重载,所以谁知道呢。)
Tl;DR;
clang 是正确的,逻辑是 [dcl.spec.auto]
允许并限制推导的 return 类型添加 [dcl.spec.auto]p11 否则没有限制,因此这是不受变量情况的限制。
见my more complete answer in the duplicate