零初始化、未命名、临时 unsigned int
Zero-initialized, unnamed, temporary unsigned int
我将 unsigned int{};
解释为 zero-initialization of a temporary unsigned int
without a name in the contexts provided below? The example does not work with clang or gcc, but compiles fine in Visual Studio: https://godbolt.org/z/LYWCCN
对吗
int ifun(int value) {
return value * 10;
}
unsigned int uifun(unsigned int value) {
return value * 10u;
}
int main() {
// does not work in gcc and clang
unsigned int{};
unsigned int ui = uifun(unsigned int{});
// works with all three compilers, also unsigned{}; works
int{};
int i = ifun(int{});
}
Clang 和 Gcc 是对的。 unsigned int{};
首先被认为是 explicit type conversion,它只适用于单字类型名称;虽然 unsigned int
(和 int*
等)不是,但 int
是。
(强调我的)
5) A single-word type name followed by a braced-init-list is a prvalue of the specified type designating a temporary (until C++17)
whose result object is (since C++17)
direct-list-initialized with the specified braced-init-list.
作为解决方法,您可以
using unsigned_int = unsigned int;
unsigned_int{};
作为结果,它将按您的预期值初始化(零初始化)一个临时 unsigned int
。
您可以使用类型别名来绕过限制。
using UI = unsigned int;
UI{};
UI ui = uifun(UI{});
我将 unsigned int{};
解释为 zero-initialization of a temporary unsigned int
without a name in the contexts provided below? The example does not work with clang or gcc, but compiles fine in Visual Studio: https://godbolt.org/z/LYWCCN
int ifun(int value) {
return value * 10;
}
unsigned int uifun(unsigned int value) {
return value * 10u;
}
int main() {
// does not work in gcc and clang
unsigned int{};
unsigned int ui = uifun(unsigned int{});
// works with all three compilers, also unsigned{}; works
int{};
int i = ifun(int{});
}
Clang 和 Gcc 是对的。 unsigned int{};
首先被认为是 explicit type conversion,它只适用于单字类型名称;虽然 unsigned int
(和 int*
等)不是,但 int
是。
(强调我的)
5) A single-word type name followed by a braced-init-list is a prvalue of the specified type
designating a temporary (until C++17)
whose result object is (since C++17)
direct-list-initialized with the specified braced-init-list.
作为解决方法,您可以
using unsigned_int = unsigned int;
unsigned_int{};
作为结果,它将按您的预期值初始化(零初始化)一个临时 unsigned int
。
您可以使用类型别名来绕过限制。
using UI = unsigned int;
UI{};
UI ui = uifun(UI{});