Problem with returning superior-scope

Hi again, trouble!

When I return any object from a superior-scope it is destructed before get it, hmm, I dunno how to explain, see:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;

class Foo
{
	public:

	int* Array;

	Foo()
	{
		Array = new int [16];  // Only a example, fixed in 16 at example.
		
		cout << "Construction of " << (unsigned) Array << endl;
	}

	~Foo()
	{
		cout << "Destruction of " << (unsigned) Array << endl;

		delete [] Array;
	}

	void operator=(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?

I need to solve it!


Last edited on
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.

Read this article:
http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29?banner=none
Thanks for that, solved :)
Topic archived. No new replies allowed.