Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling constructor with "()" is different from "{}"

Why are different results printed with these two lines of code?

std::cout << std::string{6, 's'}
std::cout << std::string(6, 's')
like image 800
cppxor2arr Avatar asked Dec 04 '22 22:12

cppxor2arr


1 Answers

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.

like image 166
Some programmer dude Avatar answered Dec 28 '22 10:12

Some programmer dude