gpt4 book ai didi

c++ - 为什么在 VS2019 中 std::initializer_list 的初始化似乎失败了

转载 作者:行者123 更新时间:2023-12-01 15:10:13 28 4
gpt4 key购买 nike

以下代码在以 Release模式编译的 Visual Studio 2019 上失败。

#include <iostream>
#include <iterator>
#include <initializer_list>

int main( int, char** )
{
std::initializer_list<int> v = {};
std::initializer_list<int> i = { 1, 2, 3 };

v = i;
std::copy( v.begin(), v.end(), std::ostream_iterator<int>( std::cout, " " ) );
std::cout << std::endl;

v = { 1, 2, 3 };
std::copy( v.begin(), v.end(), std::ostream_iterator<int>( std::cout, " " ) );
std::cout << std::endl;
}
v 的第二次初始化似乎失败了,输出如下:
1 2 3
17824704 10753212 0
但是在 Debug模式下构建或使用其他编译器(gcc、clang)构建时。输出如预期:
1 2 3
1 2 3
这可能是什么原因?

最佳答案

为了清楚起见,v 的唯一初始化发生在以下行:

std::initializer_list<int> v = {};
另外两个是赋值而不是初始化:
v = i;
v = { 1, 2, 3 };
正是这两个任务之间的差异提供了解决方案。
复制初始化列表不一定复制底层元素 - 初始化列表通常是轻量级的,并且经常仅作为指针和长度实现。
所以当你分配时, iv , i 的底层数组(因此 v )继续存在,直到在 main 结束时超出范围.那里没有问题。
当您复制 {1, 2, 3}v ,底层数组也将继续存在,直到超出范围。不幸的是,一旦赋值完成,这就会发生,这意味着使用 v 的元素在那之后会有问题。
虽然 v很可能仍然有一个指针和长度,指针指向的东西已经超出范围,并且该内存很可能已被重用于其他东西。

标准( C++20 [dcl.init.list] /6 )中的相关文本在谈论初始化列表时指出:

The [underlying] array has the same lifetime as any other temporary object, except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary.


由于您所做的不是初始化,因此不会发生此生命周期延长。
这意味着底层数组的破坏被 C++20 [class.temporary] /4 覆盖。 :

Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.



有趣的是, cplusplus.com site for initializer_list目前有关于这个确切问题的错误代码(我已经向他们提出了这个问题,不确定他们何时甚至是否会修复它):
// initializer_list example
#include <iostream> // std::cout
#include <initializer_list> // std::initializer_list

int main ()
{
std::initializer_list<int> mylist;
mylist = { 10, 20, 30 };
std::cout << "mylist contains:";
for (int x: mylist) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
虽然这在某些情况下可能有效,但绝不能保证,事实上, gcc 10.2 (检查 Compiler Explorer )正确地将其视为有问题的:
<source>: In function 'int main()':
<source>:8:25: warning: assignment from temporary 'initializer_list'
does not extend the lifetime of the underlying array
[-Winit-list-lifetime]
8 | mylist = { 10, 20, 30 };
| ^

关于c++ - 为什么在 VS2019 中 std::initializer_list 的初始化似乎失败了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63445675/

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