initializer_list类型详解

This type is used to access the values in a C++ initialization list, which is a list of elements of type const T

1、类型的自动创建
Objects of this type are automatically constructed by the compiler from initialization list declarations, which is a list of comma-separated elements enclosed in braces:

auto il = { 10, 20, 30 };  // the type of il is an initializer_list 

2、定义在头文件中,但是可以不用声明就进行调用

3、initializer_list 类型变量之间的拷贝:对同一个对象的引用,不会增加新的copy,只是语义上的拷贝

copying an initializer_list object produces another object referring to the same underlying elements, not to new copies of them (reference semantics).

4、生命周期 lifetime
The lifetime of this temporary array is the same as the initializer_list object.

5、构造器:相对于其他类型的构造器具有优先权

struct myclass {
  myclass (int,int);
  myclass (initializer_list);
  /* definitions ... */
};
myclass foo {10,20};  // calls initializer_list ctor
myclass bar (10,20);  // calls first constructor 

6、操作
initializer_list类型详解_第1张图片
7、作为模板类型,初始化时需要进行类型说明

#include  //必须包含的头文件之一,有string类存在
void error_msg(initializer_list<string> ls) //输出错误信息
{
    for (auto beg = ls.begin(); beg != ls.end(); ++beg)
    {
        std::cout << *beg << " ";
    }
    cout << std::endl;
}

    initializer_list<string> ls = { "error  1","error  2" ,"error  3" ,"error  3" ,"error  1" }; //定义类型及其初始化
    initializer_list<int> li;
    error_msg(ls);

    // 向initializer_list中传递参数注意点:{} 括起来
    string expected = "expected";
    string actual = "expected";
    if (expected != actual)
    {
        error_msg({ "functionX",expected, actual });
    }
    else
    {
        error_msg({ "functionX",expected, actual });
    }

你可能感兴趣的:(个人尝试)