Why are different results printed with these two lines of code?
std::cout << std::string{6, 's'}
std::cout << std::string(6, 's')
Because std::string
have a constructor taking an std::initializer_list
, the first example will use that constructor to create a string object with two characters. Initialization like this is called list initialization.
The second example will create a string object with six characters, all initialized to 's'
. This form of initialization is called direct initialization.
List initialization and direct initialization can be the same, except that the possible conversions for larger types to smaller types are forbidden for list initialization, and as noticed here if the class have a constructor taking an std::initializer_list
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With