return reference from function

Hy,
referring to this code

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
#include <vector>
#include <iostream>

using namespace std;

typedef vector<int> intVector;

class tmpClass {
public:
	intVector test[2]; 
	intVector & testF(){ return test[0];}
};
	
int main(int argn, char *argv[])
{
	tmpClass tmp;
	vector<int> a;
	a.push_back(1);
	a.push_back(2);
	vector<int> b;
	b.push_back(3);
	b.push_back(4);

	tmp.test[0] = a;
	tmp.test[1] = b;
			
	intVector& result = tmp.testF();
	intVector result1 = tmp.testF();
	
        tmp.test[0].push_back(10);

	for(int i = 0; i<result.size();i++) cout << result[i];

	cout << endl;

	for(int i = 0; i<result1.size();i++) cout << result1[i];
	return 0;
}


This compiles and runs fine. (Output 1210/n12).
Why does the compiler not complain at intVector result1 = tmp.testF() ?

thanks for any hint!
dziadgba
Because of this:

1
2
intVector result1 = tmp.testF();
intVector result1(tmp.testF()); //same as above 


Calls the copy constructor (operator = would work too) by adding a const to the reference you are returning.
Thanks!
Topic archived. No new replies allowed.