从两个元素初始值设定项列表初始化字符串
Initializing string from two element initializer list
我很惊讶地看到这段代码编译:
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++ 代码。
相关文章:
- C++:如何使函数只返回作为列表一部分的字符串
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 在 c++ 中多次更改字符串列表
- C++未知长度字符串的数组,其行为类似于 Python 字符串列表
- 如何将包含括号的字符串列表平展为单个列表?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- (C++) 字符串文本与参数列表不匹配
- C++使用旧编译器GCC 4.4.0在结构列表中查找字符串
- 如何存储字符串列表
- 如何在数组或链接列表中查找特定字符串
- C++ EnumWindows,将列表存储在字符串数组中
- 给定字符串和单词 S 的列表,检查列表中是否存在 S
- C 需要帮助的作业程序,该程序在文件列表中读取并在每个双重的双重列表中添加一个字符串
- 查找可变参数列表的字符串格式指定符
- 在链接列表中添加字符串的简单方法
- 嵌套列表(字符串向量的向量)初始化失败
- 通过单词列表将两个字符串移动以比较每个单词
- 链接的列表字符串分类问题
- 穿过链接列表以查找字符串