《The C++ Programming Language》第四版第164页:
When we explicitly mention the type of an object we are initializing, we have two types to consider: the type of the object and the type of the initializer. For example:
char v1 = 12345; // 12345 is an int int v2 = 'c'; // 'c' is a char T v3 = f();
By using the {}-initializer syntax for such definitions, we minimize the chances for unfortunate conversions:
char v1 {12345}; // error : narrowing int v2 {'c'}; // fine: implicit char->int conversion T v3 {f()}; // works if and only if the type of f() can be implicitly converted to a T
我不太明白 minimize the chances for unfortunate conversions
这句话和 T v3 {f()};
的注释 works if并且仅当 f() 的类型可以隐式转换为 T
时。考虑以下两种情况:
- a) 如果 T 有一个显式构造函数接受 f() 类型的参数。
- b) 如果 f() 的类型具有到某种类型 X 的转换运算符,并且 T 具有采用 X 类型参数的构造函数。
对于这两种情况,f() 的类型不能隐式转换为 T,但是 T v3 {f()}
是合式的,所以至少 如果
部分评论似乎不合适? (也不确定if
部分是否正确。)
对于这两种情况,T v3 = f();
格式错误,那么句子 minimize the chances for unfortunate conversions
在这里是什么意思?似乎 {}-initializer 实际上正在接受更多的转换形式(是否不幸是另一个问题)。 (在 v1
的情况下说明了防止缩小,这很清楚。我对 v3
感到困惑。)
最佳答案
它实际上以不同于默认方式的其他方式进行转换。
使用您的示例之一,char x = 12345;
实际上会将此值减少到最后 8 位,因为这是 char 的大小。使用 {}
符号时,它会引发错误,因为它不合适。
这不是有时(绝对)用于获得特殊效果,因此它在新 C++ 中保留为默认选项,而新符号用于提供更好的行为并减少错误空间。
关于c++ - 需要帮助理解 "{}-initializer syntax minimizes the chances for unfortunate conversions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21858781/