Nicolai Josuttis' "The Nightmare of Initialization in C++" presentation at CppCon 2018 had, at one point, the following piece of code:
std::vector< std::string > v07 = {{ "1", "2" }};
Nicolai said the following (transcription mine):
The problem is, what happens here is, we interpret these two parameters as iterators. So these are iterators, so this is the beginning of the range, and this is the end of the range, and they should refer to the same range of characters; because characters convert implicitly to strings this will compile. If you're lucky, you'll get a coredump. If not, you've got a big problem.
He lost me there. Can somebody explain what is going on here, exactly, step by step?
Below code
std::vector< std::string > v07 = { { "1", "2" } };
is equivalent to
std::string s = {"1","2"}; // call string(const char*, const char*) std::vector<std::string> v07 = {s}; // initializer list with one item
the issue is with
s={"1","2"};
This calls string(const char* start, const char* end)
constructor, but start
and end
must refer to the same string object. "1" and "2" are two different objects, so it leads to UB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With