I am confused by the following code:
#include <iostream>
#include <memory>
#include <vector>
std::shared_ptr<float> test()
{
std::vector<float> vec(10);
vec[0] = 10.1;
vec[1] = 5.0;
float* p = &vec[0];
std::shared_ptr<float> p_shared(p, [](void* ptr){});
std::cout<<"Get value 0th: "<<p_shared.get()[0]<<" , 1st: "<<p_shared.get()[1]<< std::endl;
return p_shared;
}
int main()
{
std::shared_ptr<float> p1 = test();
p1.get()[1] = 9.0;
std::cout<<"Get value 0th: "<<p1.get()[0]<<" , 1st: "<<p1.get()[1]<<std::endl;
std::cout<<"End of program"<<std::endl;
}
Get value 0th: 10.1 , 1st: 5
Get value 0th: 0 , 1st: 9
End of program
I don't understand why shared_ptr can be used to access the memory after its freed. Does that mean shared_ptr actually extends the lifetime of vec?