🐭 简单变量初始化
在 C++ 中初始化一个变量一般有多种方式,而且有时候这些初始化方式背后的行为逻辑是不一样的,尤其是类对象的初始化。统一初始化语义的引入改善了一些问题,但是同时也带来了一些问题,需要注意。
代码示例 :
#include <atomic>#include <iostream>#include <vector>int main(void) {using std::cout, std::is_same_v;cout.setf(std::ios_base::boolalpha);// in general, variable initialization can be in "=", "()", "{}" three forms// C++11 introduces uniform initialization "{}", can be used every where// simple typeint x10 = 1;int x11(1);int x12{1};int x13 = {1};// avoid narrowing conversionsint x20 = 5.0;int x21(5.0);// int x22 = {5.0}; // compile error// int x23{5.0}; // compile error// none copy constructible typestd::atomic<int> x30 = 1; // C++11 error, C++17 works because of Copy Elisionstd::atomic<int> x31(1);std::atomic<int> x32{1};std::atomic<int> x33 = {1};// std::atomic<int> x34 = x32; // compile error// containerstd::vector<int> vi1{0, 1, 2, 3, 4};std::vector<int> vi2 = {0, 1, 2, 3, 4};// class data memberstruct Job {int y10 = 1;// int y11(1); // compile errorint y12{1};int y13 = {1};};// user defined typeJob j11; // calls default ctorJob j12 = j11; // calls copy ctorj11 = j12; // calls copy assignment// fix most vexing parseJob j22(); // most vexing parse, in fact declares a functioncout << is_same_v<decltype(j22), Job(void)> << '\n'; // trueJob j23{}; // calls default ctorreturn 0;}
:::tips 大括号统一初始化,可以用在几乎所有的地方,也避免了一些问题,适用面很广
🐂 统一初始化与类对象构造
使用统一初始化的方式来初始化一个类对象的时候,对象构造函数的大致搜寻顺序如下:
- 初始化列表构造函数
- 接收相同参数的一般构造函数
另外,使用空初始化列表时会调用默认构造函数,这个是个例外。
代码示例 :
#include <initializer_list>#include <iostream>#include <string>#include <string_view>#include <vector>int main(void) {using std::initializer_list, std::string, std::string_view;struct Job {int id_{0};Job() = default; // 5th choiceJob(const int id, string_view sv) : id_{id} {}; // 4th choiceJob(const int id, const double y) : id_{id} {}; // 3rd choiceJob(const int id, const int y) : id_{id} {}; // 2nd choiceJob(const initializer_list<int> &li) : id_{*(li.begin())} {}; // 1st choice};Job j11{2, 3}; // calls 1st choice ctorJob j12(2, 3); // calls 2nd choice ctor// Job j21 { 2, 3.0 } // calls 1st choice ctor, compile error (narrowing conversion)Job j22(2, 3.0); // calls 3rd choice ctorJob j31{2, "3.0"}; // calls 4th choice ctor, not like narrowing convert caseJob j32(2, "3.0"); // calls 4th choice ctorJob j41(); // calls 5th choice ctorJob j42{}; // calls 5th choice ctorreturn 0;}
:::tips
- 初始化列表构造函数具有较高的优先级,需要小心对待,比如 std::vector 的 ‘()’ 与 ‘{}’ 构造
- 同时要注意区分 ‘{}’ 与 ‘std::initializer_list’,前者类型可以混杂,后者类型必须相同
::: 代码示例 :
#include <iostream>#include <vector>template <typename T, typename... Ts> void createT(Ts &&... params) {T t1(std::forward<Ts>(params)...); // using '()'T t2{std::forward<Ts>(params)...}; // using '{}'std::copy(t1.cbegin(), t1.cend(), std::ostream_iterator<int>(std::cout, " "));// 20 20 20 20 20 20 20 20 20 20std::cout << '\n';std::copy(t2.cbegin(), t2.cend(), std::ostream_iterator<int>(std::cout, " "));// 10 20std::cout << '\n';}int main(void) {createT<std::vector<int>>(10, 20);return 0;}
:::tips
由于 std::vector 具有两个参数的一般构造函数,同时也具有初始化列表构造函数,后者的优先级更高
对于给定 2 个参数,使用 ‘()’ 与 ‘{}’ 来初始化 std::vector 其行为是不一样的,需要特别注意
:::
🐯 总结
- 统一初始化适应范围广,也避免了一些问题
- 对于统一初始化,初始化列表类构造函数具有更高的匹配优先级
- 不要为自定义类型设计易混淆的初始化列表类构造函数
std::vector 就是一个 ‘()’ 与 ‘{}’ 初始化易混淆的典范,使用的时候要当心 :::tips ‘=’, ‘()’, ‘{}’ 初始化使用建议:
对简单变量,建议尽量使用 ‘=’ 来初始化变量,比较明确
- 一般构造函数,建议使用 ‘()’ 来明确的调用构造函数,比较准确
- 当需要使用初始化列表构造的时候才使用 ‘{}’,比较方便 :::
