Nicolai Josuttis 在 CppCon 2018 上的“C++ 初始化的噩梦”演讲曾一度包含以下代码:
std::vector< std::string > v07 = {{ "1", "2" }};
尼古拉said the following (我的转录本):
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.
他在那里失去了我。有人可以一步一步准确地解释这里发生了什么吗?
最佳答案
以下代码
std::vector< std::string > v07 = { { "1", "2" } };
等价于
std::string s = {"1","2"}; // call string(const char*, const char*)
std::vector<std::string> v07 = {s}; // initializer list with one item
问题在于
s={"1","2"};
这会调用 string(const char* start, const char* end)
构造函数,
但是 start
和 end
必须引用同一个字符串对象。 “1”和“2”是两个不同的对象,所以会导致UB。
关于c++ - CppCon 2018,尼古拉 Josuttis : Why are these interpreted as iterators?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53319710/