从两个元素初始值设定项列表初始化字符串

Initializing string from two element initializer list

本文关键字:列表 字符串 初始化 元素 两个      更新时间:2023-10-16

我很惊讶地看到这段代码编译:

std::string s2 = {"Hello", "World"};

执行该语句会导致std::exception消息basic_string::_S_create但为什么要编译呢?

这会std::string s1 = {"Hello"};编译并似乎生成一个普通字符串,而较长的初始化列表确实会导致编译错误。

您可以创建来自两个输入迭代器的字符串(当然应该指向相同的内存范围):

template< class InputIt >
basic_string(InputIt first, InputIt last, const Allocator& alloc = Allocator());

在这种情况下,我猜两个字符串文字都转换为const char*哪个 sis 是一个有效的输入迭代器,但由于它们不属于同一范围,构造函数迟早会访问无效的内存位置,当它尝试从第一个迭代到第二个时。

但是,我无法用第二个示例重现您的问题 - 这应该是有效的 c++ 代码。