The different construction syntaxes in C++ have always confused me a bit. In another question, it was suggested to try initializing a string like so
std::string foo{ '\0' };
This works and produces the intended result: a string of length 1 containing only the null character. In testing the code, I accidentally typed
std::string foo('\0');
This compiles fine (no warnings even with -Wall
), but terminates at runtime with
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted (core dumped)
Now, as far as I can tell, there is no constructor for std::string
which takes a single character as an argument, and this hypothesis is further confirmed when I attempt to pass the character indirectly.
char b = '\0';
std::string a(b);
This produces a nice, lengthy compile error. As does this
std::string a('z');
So my question is: what allows std::string a('\0');
to compile, and what makes it different from std::string a{ '\0' };
?
Footnote: Compiling using g++
on Ubuntu. This doesn't strike me as a compiler bug, but just in case...