I recently worked on a C ++ project and stumbled upon an edge case with string constructors that I cannot fully understand. The corresponding code (which you can run here ) is as follows:
#include <iostream>
#include <string>
using namespace std;
int main() {
string directParens(1, '*');
string directBraces{1, '*'};
string indirectBraces = {1, '*'};
cout << directParens.size() << endl;
cout << directBraces.size() << endl;
cout << indirectBraces.size() << endl;
return 0;
}
The string versions initialized in parentheses end with two characters in them: a charwith a numeric value of 1 followed by a star.
I donβt understand why strings initialized in parentheses refer to a constructor initializer_list, and not to a constructor that takes a size and a character. The constructor initializer_listhas the following signature:
basic_string(std::initializer_list<CharT> init,
const Allocator& alloc = Allocator());
Given what stringis an alias for basic_stringchar, the specific signature will be
string(std::initializer_list<char> init,
const Allocator& alloc = Allocator());
{1, '*'}, int char, ? , std::initializer_list - ?