Returned Temporal Objects's Lifetime

Hi,

What does the C++ standard say about returned temporal objetcts's lifetime ?

For example, in 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
39
40
41
42
43
44
45
46
47
#include <iostream>			// Object cout, manipulator endl

using std::cout;
using std::endl;

class C
{
	private:

		int i;

	public:

		C(int i){
			this->i = i;
			cout << "C(), i = " << this->i << endl;
		};

		C(const C& c){
			cout << "C(const C&), i = " << this->i << endl;
		};

		~C(){
			cout << "~C(), i = " << this->i << endl;
		};

		C& operator=(const C& c){
			cout << "operator=(const C&), i = " << this->i << endl;
			return (*this);
		};
};

C f(){
	cout << "f()" << endl;
	return C(1);
}

void h(C& c){
	cout << "h()" << endl;
};

int main(int argc, char** argv, char** envp)
{
	h(f());
	cout << "END" << endl;
	return 0;
}


The output in my platform (Windows 7 Ultimate 64 bits Service Pack 1 in a x86 PC compatible machine with an AMD Phenom II 1090T X6 3.2Ghz microprocessor; source code compiled with Microsoft Visual C++ Express IDE) is:


f()
C(), i = 1
h()
~C(), i = 1
END


Here, the temporal object C returned by function f() still lives when function h() is called and is destroyed inmediately after function h() returns to his caller (the function main()). So, it seems that a returned temporal object lives while it is used and it is destroyed when not used (in the next sentence of the sentence that call the function that returns the temporal object). Does the C++ standard specify that this must be the behaviour of C++ compilers?

Thanks.
DavidIRE wrote:
What does the C++ standard say about returned temporal objetcts's lifetime ?

12.3[class.temporary]/3-5, it's fairly long, but the first point is the one that applies here:

iso wrote:
Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.


DavidIRE wrote:
C returned by function f() still lives when function h() is called and is destroyed inmediately after function h() returns to his caller


The function call to f() is a part of the full-expression h(f()), so the temporary that is created when f() returns by value is destroyed after the function call to h() ends.
Last edited on
Topic archived. No new replies allowed.