I have the following code, why is the range based output is not what is stored in the vector?
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
shared_ptr<vector<double>> get_ptr() {
vector<double> v{1, 2, 3, 4, 5};
return make_shared<vector<double>>(v);
}
int main() {
auto vec = get_ptr();
for (int i = 0; i<get_ptr()->size(); ++i) {
std::cout << (*get_ptr())[i] << std::endl;
}
for (auto v: (*get_ptr())) {
std::cout << v << std::endl;
}
}
The output on my ubuntu is something like below,
1
2
3
4
5
4.67913e-310
4.67913e-310
3
4
5
Every time you call get_ptr()
you create a new and unique copy of the vector. And that object will be destructed as soon as the full expression involving the call is finished.
So in the case of
for (auto v: (*get_ptr()))
As soon as *get_ptr()
is finished, the object will be destructed.
And due to how ranged for loops works, you will iterate using a non-existing vector, leading to undefined behavior.