为什么列表初始化(使用花括号)比替代选择更好? [英] Why is list initialization (using curly braces) better than the alternatives?

查看:246
本文介绍了为什么列表初始化(使用花括号)比替代选择更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  MyClass a1 {a}; //比其他三个更清晰,更不容易出错
MyClass a2 = {a};
MyClass a3 = a;
MyClass a4(a);



为什么?



我找不到答案,所以让我回答自己的问题。

解决方案

基本上复制和粘贴来自Bjarne Stroustrup的C ++程序设计语言第4版:



列表初始化不允许缩小.8.5.4)。也就是:




  • 整数不能转换为不能容纳其值的另一个整数。例如,允许char
    到int,但不允许int到char。

  • 浮点值不能转换为不能容纳其$ b的浮点类型$ b值。例如,允许float为double,但不能为double。

  • 浮点值无法转换为整数类型。

  • 整数值不能转换为浮点类型。



示例:

  void fun(double val,int val2){

int x2 = val; // if val == 7.9,x2 become 7(bad)

char c2 = val2; // if val2 == 1025,c2 become 1(bad)

int x3 {val}; //错误:可能截断(好)

char c3 {val2}; //错误:可能变窄(好)

char c4 {24}; // OK:24可以表示为一个char(好)

char c5 {264}; //错误(假设8位字符):264不能为
//表示为char(好)

int x4 {2.0}; // error:no double to int value conversion(good)

}






只有 情况,其中=是首选的{}是使用 auto



例如:

  auto z1 { 99}; // z1是initializer_list< int> 
auto z2 = 99; // z2 is an int






结论



优先{}初始化替代品,除非你有强烈的理由不要。


MyClass a1 {a};     // clearer and less error-prone than the other three
MyClass a2 = {a};
MyClass a3 = a;
MyClass a4(a);

Why?

I couldn't find an answer on SO, so let me answer my own question.

解决方案

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

List initialization does not allow narrowing (§iso.8.5.4). That is:

  • An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char.
  • A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float.
  • A floating-point value cannot be converted to an integer type.
  • An integer value cannot be converted to a floating-point type.

Example:

void fun(double val, int val2) {

    int x2 = val; // if val==7.9, x2 becomes 7 (bad)

    char c2 = val2; // if val2==1025, c2 becomes 1 (bad)

    int x3 {val}; // error: possible truncation (good)

    char c3 {val2}; // error: possible narrowing (good)

    char c4 {24}; // OK: 24 can be represented exactly as a char (good)

    char c5 {264}; // error (assuming 8-bit chars): 264 cannot be 
                   // represented as a char (good)

    int x4 {2.0}; // error: no double to int value conversion (good)

}


The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.

Example:

auto z1 {99}; // z1 is an initializer_list<int>
auto z2 = 99; // z2 is an int


Conclusion

Prefer {} initialization over alternatives unless you have a strong reason not to.

这篇关于为什么列表初始化(使用花括号)比替代选择更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆