🐭 简单变量初始化

在 C++ 中初始化一个变量一般有多种方式,而且有时候这些初始化方式背后的行为逻辑是不一样的,尤其是类对象的初始化。统一初始化语义的引入改善了一些问题,但是同时也带来了一些问题,需要注意。
代码示例 :

  1. #include <atomic>
  2. #include <iostream>
  3. #include <vector>
  4. int main(void) {
  5. using std::cout, std::is_same_v;
  6. cout.setf(std::ios_base::boolalpha);
  7. // in general, variable initialization can be in "=", "()", "{}" three forms
  8. // C++11 introduces uniform initialization "{}", can be used every where
  9. // simple type
  10. int x10 = 1;
  11. int x11(1);
  12. int x12{1};
  13. int x13 = {1};
  14. // avoid narrowing conversions
  15. int x20 = 5.0;
  16. int x21(5.0);
  17. // int x22 = {5.0}; // compile error
  18. // int x23{5.0}; // compile error
  19. // none copy constructible type
  20. std::atomic<int> x30 = 1; // C++11 error, C++17 works because of Copy Elision
  21. std::atomic<int> x31(1);
  22. std::atomic<int> x32{1};
  23. std::atomic<int> x33 = {1};
  24. // std::atomic<int> x34 = x32; // compile error
  25. // container
  26. std::vector<int> vi1{0, 1, 2, 3, 4};
  27. std::vector<int> vi2 = {0, 1, 2, 3, 4};
  28. // class data member
  29. struct Job {
  30. int y10 = 1;
  31. // int y11(1); // compile error
  32. int y12{1};
  33. int y13 = {1};
  34. };
  35. // user defined type
  36. Job j11; // calls default ctor
  37. Job j12 = j11; // calls copy ctor
  38. j11 = j12; // calls copy assignment
  39. // fix most vexing parse
  40. Job j22(); // most vexing parse, in fact declares a function
  41. cout << is_same_v<decltype(j22), Job(void)> << '\n'; // true
  42. Job j23{}; // calls default ctor
  43. return 0;
  44. }

:::tips 大括号统一初始化,可以用在几乎所有的地方,也避免了一些问题,适用面很广

:::

🐂 统一初始化与类对象构造

使用统一初始化的方式来初始化一个类对象的时候,对象构造函数的大致搜寻顺序如下:

  1. 初始化列表构造函数
  2. 接收相同参数的一般构造函数

另外,使用空初始化列表时会调用默认构造函数,这个是个例外。
代码示例 :

  1. #include <initializer_list>
  2. #include <iostream>
  3. #include <string>
  4. #include <string_view>
  5. #include <vector>
  6. int main(void) {
  7. using std::initializer_list, std::string, std::string_view;
  8. struct Job {
  9. int id_{0};
  10. Job() = default; // 5th choice
  11. Job(const int id, string_view sv) : id_{id} {}; // 4th choice
  12. Job(const int id, const double y) : id_{id} {}; // 3rd choice
  13. Job(const int id, const int y) : id_{id} {}; // 2nd choice
  14. Job(const initializer_list<int> &li) : id_{*(li.begin())} {}; // 1st choice
  15. };
  16. Job j11{2, 3}; // calls 1st choice ctor
  17. Job j12(2, 3); // calls 2nd choice ctor
  18. // Job j21 { 2, 3.0 } // calls 1st choice ctor, compile error (narrowing conversion)
  19. Job j22(2, 3.0); // calls 3rd choice ctor
  20. Job j31{2, "3.0"}; // calls 4th choice ctor, not like narrowing convert case
  21. Job j32(2, "3.0"); // calls 4th choice ctor
  22. Job j41(); // calls 5th choice ctor
  23. Job j42{}; // calls 5th choice ctor
  24. return 0;
  25. }

:::tips

  1. 初始化列表构造函数具有较高的优先级,需要小心对待,比如 std::vector 的 ‘()’ 与 ‘{}’ 构造
  2. 同时要注意区分 ‘{}’ 与 ‘std::initializer_list’,前者类型可以混杂,后者类型必须相同

::: 代码示例 :

  1. #include <iostream>
  2. #include <vector>
  3. template <typename T, typename... Ts> void createT(Ts &&... params) {
  4. T t1(std::forward<Ts>(params)...); // using '()'
  5. T t2{std::forward<Ts>(params)...}; // using '{}'
  6. std::copy(t1.cbegin(), t1.cend(), std::ostream_iterator<int>(std::cout, " "));
  7. // 20 20 20 20 20 20 20 20 20 20
  8. std::cout << '\n';
  9. std::copy(t2.cbegin(), t2.cend(), std::ostream_iterator<int>(std::cout, " "));
  10. // 10 20
  11. std::cout << '\n';
  12. }
  13. int main(void) {
  14. createT<std::vector<int>>(10, 20);
  15. return 0;
  16. }

:::tips 由于 std::vector 具有两个参数的一般构造函数,同时也具有初始化列表构造函数,后者的优先级更高
对于给定 2 个参数,使用 ‘()’ 与 ‘{}’ 来初始化 std::vector 其行为是不一样的,需要特别注意 :::

🐯 总结

  1. 统一初始化适应范围广,也避免了一些问题
  2. 对于统一初始化,初始化列表类构造函数具有更高的匹配优先级
  3. 不要为自定义类型设计易混淆的初始化列表类构造函数
  4. std::vector 就是一个 ‘()’ 与 ‘{}’ 初始化易混淆的典范,使用的时候要当心 :::tips ‘=’, ‘()’, ‘{}’ 初始化使用建议:

  5. 对简单变量,建议尽量使用 ‘=’ 来初始化变量,比较明确

  6. 一般构造函数,建议使用 ‘()’ 来明确的调用构造函数,比较准确
  7. 当需要使用初始化列表构造的时候才使用 ‘{}’,比较方便 :::