我编写了一个 c++ 函数,它组装一些数据,然后将 a 返回std::shared_ptr
到一个新分配std::vector
的包含数据的地方。与此类似的东西:
std::shared_ptr<std::vector<int>> shared_ptr_to_std_vector_of_ints()
{
auto v = std::make_shared<std::vector<int>>();
for (int i = 0; i < 3; i++) v->push_back(i);
return v;
}
我尝试使用基于范围的 for 循环来迭代向量的内容,但它表现得好像向量是空的。在摆弄之后,我发现我可以通过将函数返回的值分配给局部变量,然后在循环中引用它来让它按预期运行:
// Executes loop zero times:
std::cout << "First loop:" << std::endl;
for (int i : *shared_ptr_to_std_vector_of_ints()) std::cout << i << std::endl;
// Prints three lines, as expected
std::cout << "Second loop:" << std::endl;
auto temp = shared_ptr_to_std_vector_of_ints();
for (int i : *temp) std::cout << i << std::endl;
剪断打印:
First loop:
Second loop:
1
2
3
为什么第一个版本不起作用?
我在 macOS Sierra 10.12.6 上使用 Xcode。我相信它正在使用 LLVM 9.0 来编译 c++ 代码。