Recently, I found a bug in my code due to the use of "modern" 'direct list initialization' syntax. The gist of the issue looks like this:
#include <iostream>
#include <string>
int main()
{
std::cout << std::string(static_cast<std::size_t>(2), 'y');
std::cout << std::string{static_cast<std::size_t>(2), 'x'};
return 0;
}
With the following compilation command:
g++ -std=c++11 main.cpp && ./a.out | xxd
I get the following result:
00000000: 7979 0278 yy.x
Where we can see that the strings were not initialized in the same way. The first one use the fill
string constructor which repeat the char 'y'
twice. But for the second one, it seems the braces are interpreted as a std::initializer_list<char>
, hence the 0x02
in the binary output.
Both g++
and clang++
produce the same behavior, so I suppose this is to be expected.
The question is then, how do I know if/when my braces are interpreted as an argument list for a constructor or as a single std::initializer_list
?