Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 string initialization

Tags:

c++

string

c++11

I need to create a string of 100 A characters.

Why does the following

std::string myString = {100, 'A'};

give different results than

std::string myString(100, 'A');

?

like image 507
Victor Lyuboslavsky Avatar asked Mar 13 '13 16:03

Victor Lyuboslavsky


2 Answers

std::string myString = {100, 'A'};

is initialization using initializer list. It creates a string with 2 characters: one with code 100 and 'A'

std::string myString(100, 'A');

calls the following constructor:

string (size_t n, char c);

which creates a string with 100 'A's

like image 181
user2155932 Avatar answered Oct 20 '22 17:10

user2155932


The first initializes it to values of 100 and A and the second calls a constructor overload of std::string.

like image 1
Tony The Lion Avatar answered Oct 20 '22 18:10

Tony The Lion