article 7 distinguishing between using () and {} Creating an ObjectBasic Knowledge
The following initialization methods are now known:
int x (0); int 0 ; int z{0}; int z = {0// the same as above
The assignment operation was not called during initialization with "=", as shown in the following example:
// default ctor // copy ctor // assignment, operator =
can also be used to initialize:
classWidget {intx{0};//Fine inty =0;//Fine intZ0);//Error};std::atomic<int> ai1{0};//Finestd::atomic<int> Ai2 (0);//Finestd::atomic<int> AI3 =0;//Error
In the constructor, () and {} have the same meaning when the std::initializer_list is not contained. However, if Std::initializer_list is present, it is more inclined to invoke the overloaded function when using {} to initialize the syntax. Even those copy and move constructors are hijacked, for example:
classWidget { Public: Widgets (intIBOOLb); Widgets (intIDoubled); Widget (Std::initializer_list<Long Double>IL); operator float()Const;}; Widget W5 (W4); //copy ctorWidget W6{W4};//Initializer_list<long double>, W4, float
The Std::initializer_list constructor is so strong that the optimal matching function is not it, and the error is due to narrowing the match:
Widgets (std::initializer_list<bool> IL); Widget w{5.0// error, narrowing conversions
The compiler looks for the original function only if it cannot be matched by a transform:
Widgets (std::initializer_list<std::string> il); Widget w{5.0// OK
In the case of NULL values:
// default ctor // default ctor // Most vexing parse! function
Summary
- {} Initializes at most initialization syntax, it cannot be reduced to a narrowing conversion (narrowing conversion), and is immune to some annoying parsing (most vexing parse)
- During constructor overloading parsing, {} initializes the first match std::initializer_list, even if other constructors match
- using () or {} to create a std::vector<numeric type> can be a big difference
- Selecting () or {} In the template creates an object is a challenge
[Effective modern C + +] Item 7. Distinguish between () and {} When creating objects-distinguish between using () and {} creating objects