std :: pair中的初始化列表 [英] Initializer list inside std::pair
问题描述
此代码:
#include <iostream>
#include <string>
std::pair<std::initializer_list<std::string>, int> groups{ { "A", "B" }, 0 };
int main()
{
for (const auto& i : groups.first)
{
std::cout << i << '\n';
}
return 0;
}
编译但返回段错误.为什么?
compiles but returns segfault. Why?
在gcc 8.3.0和在线编译器上进行了测试.
Tested on gcc 8.3.0 and on online compilers.
推荐答案
std :: initializer_list
并不意味着要存储,它仅用于...很好的初始化.在内部,它仅存储指向第一个元素和大小的指针.在您的代码中, std :: string
对象是临时对象,而 initializer_list
既不拥有它们的所有权,也不延长其寿命,也不复制它们(因为它不是容器),因此它们在创建后立即超出范围,但是您的 initializer_list
仍然保留指向它们的指针.这就是为什么您会遇到细分错误.
std::initializer_list
is not meant to be stored, it is just meant for ... well initialization. Internally it just stores a pointer to the first element and the size. In your code the std::string
objects are temporaries and the initializer_list
neither takes ownership of them, neither extends their life, neither copies them (because it's not a container) so they go out of scope immediately after creation, but your initializer_list
still holds a pointer to them. That is why you get segmentation fault.
要存储,您应该使用一个容器,例如 std :: vector
或 std :: array
.
For storing you should use a container, like std::vector
or std::array
.
这篇关于std :: pair中的初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!