#include <iostream>
usingnamespace std;
class Foo
{
public:
int* Array;
Foo()
{
Array = newint [16]; // Only a example, fixed in 16 at example.
cout << "Construction of " << (unsigned) Array << endl;
}
~Foo()
{
cout << "Destruction of " << (unsigned) Array << endl;
delete [] Array;
}
voidoperator=(Foo& get)
{
cout << "Operator= called to get from " << (unsigned) get.Array << " To " << (unsigned) Array << endl;
}
// No more content, for now only a example of the ocurrence;
};
Foo Example_Problem(void)
{
Foo x; // Scope 1;
if(1)
return x; // Returning something of a superior scope causes a problem, look at the output.
return x;
}
Foo Example_Works(void)
{
Foo x;
return x;
}
int main()
{
Foo Get;
// ---> Now run the program with one of the functions at a time <---
Get = Example_Problem();
// Get = Example_Works();
cin.get();
return 0;
}
Outputs:
Using Example_Problem()
Construction of 669536
Construction of 670488
Destruction of 670488
Operator= called to get from 670488 To 669536
Destruction of 670488
After that the program stops. The debugger says corruption of heap... wow, deleting two times the same pointers.
Using Example_Works()
Construction of 9910112
Construction of 9911064
Operator= called to get from 670488 To 669536
Destruction of 9911064
[pause]
Destruction of 9910112
In that version everything goes well ;)
What is the problem with returning something from a seperior-scope causing that?
When you return something from a function, the copy constructor can be invoked.
The default one just copies all members. In your case that means you'll have two pointers pointing to the same array.