更新时间:2023-11-10 23:08:34
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
.