从两个元素初始化器列表初始化字符串
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*
这是一个有效的输入迭代器,但由于它们不属于同一范围,构造函数迟早会当它尝试从第一个迭代到第二个时访问无效的内存位置。
但是我无法用第二个示例重现您的问题 - 这应该是有效的 C++ 代码。
我很惊讶地看到这段代码可以编译:
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++ 代码。