Consider the following code:
int Main () { int1; int y = (1);//useless int1 }; int A; No initializer, no consideration of int B (1); int 1 }; }
Dazzled by the initialization syntax. With the initializer, the basic is: =1 (1) ={1} or {1} in several cases. The delimiter for the variable name and initializer is: = () {} These three kinds of
#include <iostream>classS { Public: S (std::initializer_list<int>il) {std::cout<<"S (std::initializer_list<int> il) called"<<Std::endl; } S (inti) {std::cout<<"S (int i) called"<<Std::endl; }};intMain () {S y=1; S Z= {1 }; S A (1); S b{1 }; }
We found that for user-defined types, with the {} initializer, the first match s (std::initializer_list<int> il). This is a wake-up call, {} is not so versatile initialization syntax. If you want to invoke the constructor of S (int), be honest with the traditional S-a (1) syntax.
#include <boost/type_index.hpp>#include<iostream>intMain () {Auto x= (1); Auto y=1; Auto Z= {1 }; Auto A (1); Auto b{1 }; usingBOOST::TYPEINDEX::TYPE_ID_WITH_CVR; Std::cout<< type_id_with_cvr< decltype (x) > (). Pretty_name () <<'\ n'; Std::cout<< type_id_with_cvr< decltype (y) > (). Pretty_name () <<'\ n'; Std::cout<< type_id_with_cvr< decltype (z) > (). Pretty_name () <<'\ n'; Std::cout<< type_id_with_cvr< Decltype (a) > (). Pretty_name () <<'\ n'; Std::cout<< type_id_with_cvr< Decltype (b) > (). Pretty_name () <<'\ n';}
Auto uses a different rule, ={1} will be deduced as Std::initializer_list<int>{1} and {1} will be deduced as (int) 1
Summary: Basic type int: ={1} {1} deduced into (int) 1
Custom type: ={1} {1} deduced to Std::initializer_list<int>{1} Note: The custom type constructor has a constructor that is std::initializer_list as a parameter, as defined by S.
Case of Auto: ={1} deduced into Std::initializer_list<int>{1}
{1} deduced as (int) 1
The rules are still complicated and difficult to remember, so it's good to be careful when you encounter the {} initializer.
C + + Initialization