Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CppCon 2018, Nicolai Josuttis: Why are these interpreted as iterators?

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?

like image 665
DevSolar Avatar asked Nov 15 '18 12:11

DevSolar


1 Answers

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.

like image 171
rafix07 Avatar answered Oct 03 '22 17:10

rafix07