c++ - CppCon 2018,尼古拉 Josuttis : Why are these interpreted as iterators?

标签 c++ initialization c++17

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) 构造函数, 但是 startend 必须引用同一个字符串对象。 “1”“2”是两个不同的对象,所以会导致UB。

关于c++ - CppCon 2018,尼古拉 Josuttis : Why are these interpreted as iterators?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53319710/

相关文章:

c++ - 是否有用于将 FLAC 转码为 MP3 的简单 C 或 C++ 库?

c++ - 为什么移动超过允许的位仍然有效?

c# - null 和未初始化的区别?

c++ - 如何在派生类的函数中使用基类的静态常量字段作为数组的大小?

c++ - 如何重载 == 运算符而不使其成为友元函数?

c++ - 为 boost HashMap 定义自定义哈希函数

c++ - 更改 boost vector 的构造函数

c++ - 为什么我不能用大括号括起来的初始化列表构造队列/堆栈? (C++11)

c++ - Constexpr 类采用 const 引用未编译

c++ - std::set 使用派生类对象,但使用 gcc8.1 进行基类比较