• 【C++ 学习 ㉘】- 详解 C++11 的列表初始化


    目录

    一、C++11 简介

    二、列表初始化

    2.1 - 统一初始化

    2.2 - 列表初始化的使用细节

    2.2.1 - 聚合类型的定义

    2.2.2 - 注意事项

    2.3 - initializer_list

    2.3.1 - 基本使用

    2.3.2 - 源码剖析


     


    一、C++11 简介

    1. 1998 年,C++ 标准委员会发布了第一版 C++ 标准,即 C++98 标准,并计划以后每 5 年视实际需要更新一次标准。

      所谓标准,即明确 C++ 代码的编写规范,所有的 C++ 程序员都应遵守此标准

    2. 2003 年,C++ 标准委员会发布了第二版 C++ 标准,即 C++03 标准,但由于 C++03 仅修复了一些 C++98 中存在的漏洞,并未修改核心语法,因此人们习惯将这两个标准合称为 C++98/03 标准。

    3. 2011 年,C++ 标准委员会发布了第三版 C++ 标准,即 C++11 标准,相比 C++03,C++11 带来了数量可观的变化,其中包含了约 140 个新特性,以及对 C++03 中约 600 个缺陷的修正,这使得 C++11 更像从 C++98/03 中孕育出来的一种新语言。。

      C++ 标准委员会一开始是计划在 2007 年发布第三版 C++ 标准,即 C++07 标准,但在 2006 年时,标准委员会认为到 2007 年,甚至到 2008 年,都可能无法发布第三版 C++ 标准,所以干脆将第三版 C++ 标准命名为 C++0x,即计划在二十一世纪的第一个 10 年的某个时间发布,但最终直到 2011 年才发布第三版 C++ 标准


    二、列表初始化

    在 C++98/03 中,对象的初始化方式有很多种,这些不同的初始化方式都有各自的适用范围和作用,没有一种方式可以通用于所有情况。为了统一初始化方式,并且让初始化行为具有确定的效果,C++11 提出了列表初始化的概念

    2.1 - 统一初始化

    在 C++98/03 中,对于普通数组和可以直接进行内存拷贝(memcpy)的对象,可以使用列表初始化来初始化数据。

    1. int arr[5] = { 0, 1, 2, 3, 4 };
    2. struct Point
    3. {
    4.    int _x;
    5.    int _y;
    6. } p = { 0, 0 };

    在 C++11 中,初始化列表的适用性被大大地增加了,它现在可以适用于任何类型对象的初始化

    注意:在 C++11 中,使用列表初始化时,可以添加等号(=),也可以不添加等号

    1. class A
    2. {
    3. public:
    4. A(int i = 0) : _i(i) { }
    5. private:
    6. A(const A& a) : _i(a._i) { }
    7. private:
    8. int _i;
    9. };
    10. int main()
    11. {
    12.    A a1(10);
    13.    A a2 = 10;
    14.    A a3 = { 10 };
    15.    A a4{ 10 };
    16.    return 0;
    17. }
    1. a3、a4 使用了 C++11 的列表初始化来初始化对象,效果如同 a1 的直接初始化

    2. 至于 a2,10 会通过隐式类型转换调用构造函数 A(int i = 0) 构造出一个匿名对象,然后通过这个匿名对象调用拷贝构造函数 A(const A& a) 构造出 a2,但由于拷贝构造函数是私有的(private),所以编译器会报错

      注意:Linux 中的 g++ 编译器会报错,VS 中的编译器则不会报错

    使用 new 操作符创建新对象时也可以使用列表初始化来初始化对象

    1. int* p = new int{ 0 };
    2. int* arr = new int[5]{ 0, 1, 2, 3, 4 };

    除了上面所述的内容,列表初始化还可以直接用在函数传参和返回值上

    1. #include
    2. #include
    3. using namespace std;
    4. class Person
    5. {
    6. public:
    7. Person(int id, string name) : _id(id), _name(name)
    8. {
    9. cout << _id << ":" << _name << endl;
    10. }
    11. private:
    12. int _id;
    13. string _name;
    14. };
    15. void func1(Person p) { }
    16. Person func2() { return { 2, "李四" }; }
    17. int main()
    18. {
    19.    func1({ 1, "张三" });  // 1:张三
    20. Person p = func2();  // 2:李四
    21.    return 0;
    22. }

     

    2.2 - 列表初始化的使用细节

    在 C++11 中,列表初始化的使用范围被大大地增加了,但一些模糊的概念也随之而来。

    1. #include
    2. using namespace std;
    3. struct T1
    4. {
    5. int _x;
    6. int _y;
    7. } t1{ 520, 520 };
    8. struct T2
    9. {
    10. int _x;
    11. int _y;
    12. T2(int, int) : _x(1314), _y(1314) { }
    13. } t2{ 520, 520 };
    14. int main()
    15. {
    16. cout << t1._x << ", " << t1._y << endl;  // 520, 520
    17. cout << t2._x << ", " << t2._y << endl;  // 1314, 1314
    18. return 0;
    19. }

    在上面的程序中,t1 和 t2 都使用相同的列表初始化来初始化对象,但输出的结果却不同。因为对于聚合类型的对象 t1,它可以直接使用列表初始化来初始化对象;对于非聚合类型的对象 t2,它是基于构造函数使用列表初始化来初始化对象

    2.2.1 - 聚合类型的定义

    1. 普通数组可以看作是一个聚合类型。

    2. 满足以下条件的类(class、struct、union)可以看作是一个聚合类型:

      • 无基类、无虚函数以及无用户自定义的构造函数

      • 无 private 或 protected 的普通数据成员(即非静态数据成员)

        1. struct T1
        2. {
        3. int _x;
        4. int _y;
        5. private:  // 或者 protected
        6. int _z;
        7. } t1{ 1, 2, 3 };  // error(类中有私有成员,无法使用列表初始化进行初始化)
        8. struct T2
        9. {
        10. int _x;
        11. int _y;
        12. protected:  // 或者 protected
        13. static int _z;
        14. } t2{ 1, 2 };  // ok
        15. int T2::_z = 3;  // 注意:静态数据成员 _z 不能使用列表初始化进行初始化
      • 类中不能有 {} 和 = 直接初始化的非静态数据成员(即就地初始化)

        1. struct T3
        2. {
        3. int _x = 1;
        4. int _y{ 2 };
        5. } t3{ 0, 0 };  // error(C++11)

        注意:从 C++14 开始,也可以使用列表初始化来初始化类中使用 {} 和 = 初始化过的非静态数据成员

    2.2.2 - 注意事项

    聚合类型的定义并非递归的,即当一个类的非静态数据成员是非聚合类型时,这个类也可能是聚合类型

    1. struct T1
    2. {
    3. int _x;
    4. int _y;
    5. private:
    6. int _z;
    7. public:
    8. T1() : _x(1), _y(2), _z(3) { }
    9. };
    10. struct T2
    11. {
    12. T1 _t1;
    13. double _d;
    14. };
    15. int main()
    16. {
    17. T2 t2{ {}, 3.14 };
    18. return 0;
    19. }

    可以看到,T1 是非聚合类型,因为它有一个 private 的非静态数据成员,但 T2 依然是一个聚合类型,可以直接使用列表初始化来初始化对象 t2。

    注意:使用列表初始化来初始化 t2 的非聚合类型成员 _t1 时,可以直接写一对空的大括号 {},这相当于调用 _t1 的默认构造函数

    2.3 - initializer_list

    2.3.1 - 基本使用

    当编译器看到 { t1, t2, ..., tn } 时,便会生成一个 initializer_list 类型的对象(其中 T 为元素的类型),它关联到一个 array

    1. #include
    2. using namespace std;
    3. int main()
    4. {
    5. auto il = { 10, 20, 30 };
    6. cout << typeid(il).name() << endl;  // class std::initializer_list
    7. return 0;
    8. }

    对于聚合类型,编译器会将 array 内的元素逐一分解并赋值给被初始化的对象,这相当于为该对象每个字段分别赋值

    对于非聚合类型,如果该类存在一个接收 initializer_list 类型的构造函数,则初始化时会将 initializer_list 对象作为一个整体传给构造函数;如果该类不存在这样的构造函数,则 array 内的元素会被编译器分解并传给相应的能接收这些参数的构造函数(比如列表中有 2 个元素,就传给带 2 个参数的构造函数,有 3 个元素,就传给带 3 个参数的构造函数,依次类推)

    1. #include
    2. #include
    3. using namespace std;
    4. class Test
    5. {
    6. public:
    7. Test(int) { cout << "Test(int)" << endl; }
    8. Test(int, int) { cout << "Test(int, int)" << endl; }
    9. };
    10. int main()
    11. {
    12.    // vector (initializer_list il,
    13. // const allocator_type& alloc = allocator_type());
    14. vector<int> v{ 0, 1, 2, 3, 4 };
    15. for (const auto& e : v)
    16. {
    17. cout << e << " ";
    18. }
    19.    // 0 1 2 3 4
    20. cout << endl;
    21.    
    22. Test t1{ 1 };  // Test(int)
    23. Test t2{ 1, 2 };  // Test(int, int)
    24. return 0;
    25. }

    2.3.2 - 源码剖析

    1. #include
    2. template <class T>
    3. class initializer_list
    4. {
    5. public:
    6.    typedef T        value_type;
    7.    typedef const T& reference;  // 说明对象永远为 const,不能被外部修改!
    8.    typedef const T& const_reference;
    9.    typedef size_t   size_type;
    10.    typedef const T* iterator;  // 永远为 const 类型
    11.    typedef const T* const_iterator;
    12.    
    13. private:
    14.    iterator  _M_array; // 用于存放用列表初始化中的元素
    15.    size_type _M_len;   // 元素的个数
    16.    // 注意:编译器可以调用 private 的构造函数!!!
    17.    // 构造函数在调用之前,编译会先在外部准备好一个 array,
    18.    // 同时把 array 的地址传入模板,并保存在 _M_array 中
    19.    constexpr initializer_list(const_iterator __a, size_type __l)
    20.       :_M_array(__a), _M_len(__l) {};  // 注意该构造函数被放到 private 中!
    21.    
    22. public:
    23.    // 无参的构造函数
    24.    constexpr initializer_list() : _M_array(0), _M_len(0) {}
    25.    // 用于获取元素的个数
    26.    constexpr size_type size() const noexcept { return _M_len; }
    27.    // 获取第一个元素的位置
    28.    constexpr const_iterator begin() const noexcept { return _M_array; }
    29.    // 获取最后一个元素的下一个位置
    30.    constexpr const_iterator end() const noexcept
    31.   {
    32.        return begin() + _M_len;
    33.   }
    34. };

    让模拟实现的 vector 也支持列表初始化

    1. namespace yzz
    2. {
    3. template<class T>
    4. class vector
    5. {
    6. public:
    7. typedef T* iterator;
    8. typedef const T* const_iterator;
    9. vector(std::initializer_list il) :
    10. _start(new T[il.size()]),
    11. _finish(_start + il.size()),
    12. _end_of_storage(_finish)
    13. {
    14. iterator v_it = _start;
    15. typename std::initializer_list::iterator il_it = il.begin();
    16. while (il_it != il.end())
    17. {
    18. *v_it++ = *il_it++;
    19. }
    20. }
    21.        // ... ...
    22. private:
    23. iterator _start;
    24. iterator _finish;
    25. iterator _end_of_storage;
    26. };
    27. }
  • 相关阅读:
    k8s客户端配置
    【Hack The Box】windows练习-- Optimum
    DDOS直接攻击系统资源
    对象映射 - Mapping.Mapster
    xv6---Lab2: system calls
    “Invalid project description“问题解决
    qnx sh: rm: Arg list too long
    Windows-Oracle11g 安装详解-含Navicate远程连接配置 -本地监听设置及更换navicate环境指向的oci.dll
    大学校园广播“录编播”与IP校园公共广播系统技术方案
    eclipse tomcat setting
  • 原文地址:https://blog.csdn.net/melonyzzZ/article/details/133893041