In the code below, function localObjReurn() returns a local object which has raw pointer to heap. When this is returned, the local object gets destroyed and the destructor deletes the heap memory and pointer. In main, steve gets a copy of this destroyed object. When steve is printed, it shows valid data and on getting destroyed at end of the scope of main, there is no crash due to multiple freeing of the same memory. Why?
#include <iostream>
#include <cstring>
class Player{
private:
char *ptr;
public:
Player(char *c)
{
ptr = new char[strlen(c) +1];
strcpy(ptr, c);
}
Player(const Player &p)
{
ptr = new char[strlen(p.ptr) + 1];
strcpy(ptr, p.ptr);
}
~Player()
{
delete [] ptr;
}
char * getData()
{
return ptr;
}
};
Player localObjReturn()
{
Player tempObj("Weinstein");
return tempObj;
}
int main()
{
Player steve {localObjReturn()};
std::cout << steve.getData();
}