0

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?

Zack
  • 1,205
  • 2
  • 14
  • 38
  • I think the question is close enough to make it a duplicate, even though there's no `delete` here. In short - the object is deleted, and trying to access it is Undefined Behaviour. Anything can happen. – Yksisarvinen Oct 20 '21 at 23:10
  • Clearly it didn't work because the second line says `0th: 0` instead of `0th: 10.1`. – Raymond Chen Oct 20 '21 at 23:10
  • That's classic **undefined behavior**. What you are looking at is buggy code. – Eljay Oct 20 '21 at 23:10

0 Answers0