I wrote a c++ function that assembles some data then then returns a std::shared_ptr
to a newly allocated std::vector
containing the data. Something analogous to this:
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;
}
I tried to iterate over the contents of the vector using a range-based for loop, but it acted as if the vector was empty. After fiddling around, I found I could get it to behave as I expected by assigning the value returned from the function to a local variable, then referencing that in the loop:
// 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;
That snipped prints this:
First loop:
Second loop:
1
2
3
Why does the first version not work?
I’m using Xcode on macOS Sierra 10.12.6. I believe it is using LLVM 9.0 to compile the c++ code.
shared_ptr
aroundstd::vector
(asstd::vector
already manage memory) ? (especially true with provided usage). – Decorative