提问人:Kyrion 提问时间:3/24/2020 更新时间:3/25/2020 访问量:112
零初始化、未命名、临时无符号 int
Zero-initialized, unnamed, temporary unsigned int
问:
在下面提供的上下文中,我是否正确地解释为没有名称的临时的零初始化?该示例不适用于 clang 或 gcc,但在 Visual Studio 中编译良好: https://godbolt.org/z/LYWCCNunsigned int{};
unsigned int
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{});
}
答:
3赞
songyuanyao
3/24/2020
#1
Clang 和 Gcc 是对的。 首先被认为是显式类型转换,它只适用于单字类型名称;虽然(和等)不是,但是。unsigned int{};
unsigned int
int*
int
(强调我的)
5) 后跟 braced-init-list 的单字类型名称是指定类型 direct-list-initialized with specified braced-init-list 的 prvalue。
designating a temporary (until C++17)
whose result object is (since C++17)
作为解决方法,您可以
using unsigned_int = unsigned int;
unsigned_int{};
因此,它将按预期值初始化(零初始化)临时值。unsigned int
评论
0赞
Rakete1111
3/25/2020
(unsigned int){}
无效,因为不是表达式。{}
0赞
ByteEater
10/28/2023
什么是?(unsigned int){5}
2赞
R Sahu
3/24/2020
#2
您可以使用类型别名来绕过此限制。
using UI = unsigned int;
UI{};
UI ui = uifun(UI{});
评论