Initialization difference with or without Curly braces in C++11

后端 未结 3 1308
野性不改
野性不改 2020-11-29 23:22

We can initialize the variable in two ways in C++11

One:

int abc = 7;

Two:

int ab         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 23:36

    While for int the existing replies are complete, I painfully found out, that in some cases, there are other differences between the () and {} initializations.

    The keyword is that {} is an initializer list.

    One such cases is, the std::string initialization with count copies of a char:

    std::string stars(5, '*')
    

    will initialize stars as *****, but

    std::string stars{5, '*'}
    

    will be read as std::string stars(char(5), '*') and initialize star as * (preceded by an hidden character).

提交回复
热议问题