gpt4 book ai didi

c++ - 从两个元素初始化器列表初始化字符串

转载 作者:搜寻专家 更新时间:2023-10-31 01:36:37 24 4
gpt4 key购买 nike

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

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* ,这是一个有效的输入迭代器,但由于它们不属于同一范围,构造函数将当它尝试从第一个迭代到第二个时,迟早会访问无效的内存位置。

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

关于c++ - 从两个元素初始化器列表初始化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35336890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com