在 for range 循环中迭代包含向量的取消引用 unique_ptr

Iterating over dereferenced unique_ptr, that contains vector, in for range loop

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

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

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

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 returns是临时的std::unique_ptr,在full-expression后会被销毁。也就是说,它管理的std::vector也会被摧毁;即使从临时 std::unique_ptr 获得的 std::vector 绑定到转发引用,其生命周期也不会延长。

从 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;