gpt4 book ai didi

c++ - 与初始化列表共享数据是否在标准范围内有效?

转载 作者:行者123 更新时间:2023-12-04 03:22:18 25 4
gpt4 key购买 nike

lst2 = lst Copying or assigning an initializer_list does not copy the elements in the list. After the copy, the original and the copy share the elements.

根据C++ Primer Table 6.1,assign one initializer list会共享数据,但是如果initializer list与另一个out-scoped共享怎么办,例如,下面的代码是函数的一部分

std::initializer_list<int> lst1;
{
std::initializer_list<int> lst2 = {1, 2, 3};
lst1 = lst2;
}

似乎初始化列表可能共享文字的数据,但标准中指定的数组文字的生命周期是多少?这段代码安全吗?

最佳答案

此代码似乎无效。这是来自 cppreference 的一些相关摘录

The underlying array is a temporary array of type const T[N], in whicheach element is copy-initialized (except that narrowing conversionsare invalid) from the corresponding element of the originalinitializer list. The lifetime of the underlying array is the same asany other temporary object, except that initializing aninitializer_list object from the array extends the lifetime of thearray exactly like binding a reference to a temporary (with the sameexceptions, such as for initializing a non-static class member).

退出内部作用域后,临时底层数组将被销毁 - 随着内部 lst2 的生命周期结束 - 而封闭作用域中的 lst1 将以悬空指针。

关于c++ - 与初始化列表共享数据是否在标准范围内有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68272403/

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