If the program leaves the scope the vec variable will be deleted and the shared pointer will delete the pointer too. As the result the program will crash due to the double free().
However, if the shared pointer is returned to another scope, we still can use the pointer, until the shared pointer realizes that the pointer isn't used anymore, see this example below:
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); cout<<"Get value 0th: "<<p_shared.get()[0]<<" , 1st: "<<p_shared.get()[1]<<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; }
Output:
Get value 0th: 10.1 , 1st: 5 Get value 0th: 0 , 1st: 9 End of program free(): double free detected in tcache 2 Aborted (core dumped)