std::string
has a constructor that takes an initializer_list
argument.
basic_string( std::initializer_list<CharT> init,
const Allocator& alloc = Allocator() );
That constructor always gets precedence when you use a braced-init-list to construct std::string
. The other constructors are only considered if the elements in the braced-init-list are not convertible to the type of elements in the initializer_list
. This is mentioned in [over.match.list]/1.
Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T
and the argument list consists of the initializer list as a single argument.
In your example, the first argument 5
is implicitly convertible to char
, so the initializer_list
constructor is viable, and it gets chosen.
This is evident if you print each character in the strings as int
s
void print(char const *prefix, string& s)
{
cout << prefix << s << ", size " << s.size() << ": ";
for(int c : s) cout << c << ' ';
cout << '\n';
}
string str1 {"aaaaa"};
string str2 {5, 'a'};
string str3 (5, 'a');
print("str1: ", str1);
print("str2: ", str2);
print("str3: ", str3);
Output:
str1: aaaaa, size 5: 97 97 97 97 97
str2: a, size 2: 5 97
str3: aaaaa, size 5: 97 97 97 97 97
Live demo