Let's say you have this code:
#include <iostream>
using namespace std;
class MyClass
{
public:
int *v;
MyClass()
{
v=new int[5];
for(int i=0;i<5;i++) v[i]=i; // x will look like : 0,1,2,3,4
}
~MyClass()
{
cout<<"Destructor called! Now v is deallocated! \n";
delete[] v;
}
};
MyClass myFunction()
{
MyClass mc;
return mc;
}
int main()
{
MyClass x;
x=myFunction();
cout<<x.v[2]<<'\n'; //it may or may not print the right thing
return 0;
}
As you can see, myFunction
returns the object mc
like you said. But you also know that the destructor of mc
will be called when mc
goes out of scope - mc
is declared inside myFunction
, so the destructor will be called after the function is executed and memory will be freed (delete[] v
). The memory is deallocated, but the values are still there in the memory! So, even though x=myFunction();
will work, you will have an object where the memory v points to is deallocated! So, cout<<x.v[2]<<'\n';
may not print the right thing. If you compile the code it will probably print the correct value (2), because the memory was not overwritten, but if you would do some more allocations before the cout statement, or after some time of using your OS, you will see that the value printed is incorrect/crash as the memory will be overwritten by other programs. v
still points to that memory block, but it doesn't know what's there because the memory is deallocated.
Inside myFunction
: v -> |0|1| 2 |3|4|...
After exiting myFunction
: v -> |0|1| 2 |3|4|.....
After some memory allocations: v -> |a|1| b |@|%|3|7|2|1|*|!|......