Since C ++ 11, the standard library containers and std::string have constructors that take a list of initializers. This constructor takes precedence over other constructors (even as @ JohannesSchaub-litb noted in the comments, even ignoring the other “best match” criteria). This leads to several well-known pitfalls when converting all forms in square brackets () constructors to their brackets of version {}
#include <algorithm> #include <iostream> #include <iterator> #include <vector> #include <string> void print(std::vector<int> const& v) { std::copy(begin(v), end(v), std::ostream_iterator<int>(std::cout, ",")); std::cout << "\n"; } void print(std::string const& s) { std::cout << s << "\n"; } int main() { // well-known print(std::vector<int>{ 11, 22 }); // 11, 22, not 11 copies of 22 print(std::vector<int>{ 11 }); // 11, not 11 copies of 0 // more surprising print(std::string{ 65, 'C' }); // AC, not 65 copies of 'C' }
I could not find a third example on this site, and this thing arose in the Lounge chat <C ++> (when discussing with @rightfold, @Abyx and @JerryCoffin). A somewhat surprising thing is that the std::string , using a counter and a character to use {} instead of () , changes its value from n copies of the character to n -th character (usually from the ASCII table), followed by a different character .
This is not caught by the usual prohibition on binding to narrowing conversions, because 65 is a constant expression that can be represented as a char and will retain its original value when converting back to int (§8.5.4 / 7, bullet 4) (thanks @JerryCoffin )
Question : are there any other examples hiding in the standard library where the conversion of the style constructor () to the style {} greedily coincides with the constructor of the list of initializers?
c ++ c ++ 11 initializer-list
TemplateRex Nov 07 '13 at 22:25 2013-11-07 22:25
source share