统一初始化和std :: initializer_list

时间:2015-09-16 09:23:11

标签: c++ c++11 initializer-list uniform-initialization

我正在学习C ++,我到了关于列表初始化的地步。 经过一些混乱之后,由于语法重叠,我明白统一初始化和列表初始化确实是两个不同的(尽管我只是说重叠)C ++ 11的新功能。 所以,在我提出我的问题之前,我想回顾一下,如果我发现错误的话,请纠正我(之前有些事情会成为对这个话题的误解......)

就内置类型而言,初始化它们的语法如下(我假设int是为了可读性):

// defines a default initialized int
int a;
// defines a value initialized int (binary zeroes)
int a{};

// equivalent definitions,define an int variable of value 10:
int a=10;
int a(10);
int a{10};
int a={10};

// equivalent definitions,define a temporary int variable of value 10:
int(10);
int{10};

// equivalent definitions,define a temporary int variable that is value initialized to 0:
int();
int{};

现在到了有趣的部分,使用聚合类型(数组和聚合结构)的统一初始化。 在C ++ 11之前,我可以使用列表初始化程序初始化arays和聚合类:

int array[]={1,2,3};

struct aggregate {
  int a;
  double b;
};

aggregate a={1,2.3};

现在,我知道新标准允许我使用新语法进行统一初始化:

int array[]{1,2,3};
aggregate a{1,2,3};

在构造函数的成员初始化列表中使用它可能会派上用场。

现在,到类类型。 如果类没有定义initializers_list构造函数:

// equivalent definitions,define a class_type variable,default initialized:
class_type name;
class_type name{};

// equivalent definitions,define a class_type variable,using the appropriate constructor:
class_type name(*args*);
class_type name{*args*};
class_type name={*args*};

// defines a class_type variable and calls copy-constructor (allows implicit conversion to class_type if converting constructor is non-explicit)
class_type name=name2;      

// equivalent definitions,define a temporary class_type object,default initialized
class_type();
class_type{};

// equivalent definitions,define a temporary class_type object,initialized by the appropriate constructor
class_type(*args*);
class_type{*args*};

我知道当一个类定义一个class_type :: class_type(const std :: initializer_list&)构造函数时,它优先于其他构造函数(除非它是一个空列表,然后默认构造函数优先)。

现在,我的问题是:

=在使用支撑列表时会发生什么变化?我能想到的唯一区别是init list构造函数是否显式。是

class_type name{*args*};
class_type name={*args*};

相同
class_type name({*args*});
class_type name=class_type(std::initializer_list({*args*}));

所以涉及复制初始化隐式转换?这是唯一的区别吗?

如果我说的话有些错误,请纠正我!

0 个答案:

没有答案