gpt4 book ai didi

c++ - 在 for range 循环中迭代包含 vector 的取消引用的 unique_ptr

转载 作者:可可西里 更新时间:2023-11-01 16:36:08 30 4
gpt4 key购买 nike

为什么这段代码不像我想象的那样工作?

for (auto it: *std::make_unique<std::vector<int>>(std::vector<int>({1, 2, 3, 4, 5})))
std::cout << it << std::endl;

vector 对象在执行循环的第一次迭代之前被销毁

最佳答案

range-based for loop相当于:

{
init-statement
auto && __range = range_expression ;
...
}

对于您的 range_expression,它将是

auto && __range = *std::make_unique<std::vector<int>>(std::vector<int>({1, 2, 3, 4, 5}));

但是

If range_expression returns a temporary, its lifetime is extended until the end of the loop, as indicated by binding to the rvalue reference __range, but beware that the lifetime of any temporary within range_expression is not extended.

std::make_unique 返回的是一个临时的std::unique_ptr,在完整表达式之后它将被销毁。这意味着它管理的 std::vector 也将被销毁;即使从临时 std::unique_ptr 获得的 std::vector 绑定(bind)到转发引用,它的生命周期也不会延长。

从 C++20 开始,您可能会使用 init-statement;比如

for (auto p = std::make_unique<std::vector<int>>(std::vector<int>({1, 2, 3, 4, 5})); auto it : *p)
std::cout << it << std::endl;

关于c++ - 在 for range 循环中迭代包含 vector 的取消引用的 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47870439/

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