temporaries:
Definition: a temporary is a C++ object which is niether a constant nor a variable, but is has type.
example1:
TYPE f(int a)
{...}
f(2) is a temporary. it is niether a constant nor a variable but it has a type.
example2:
class A
{
public:
A(char ch)
{...}
};
(A)'a' is a temporary.
properties of temporaries:
first essential property of temporaries: a temporary is destroyed as soon as possible:
example:
#include <conio.h>
#include <iostream>
using namespace std;
class Test
{
public:
int a;
Test(int x)
{
a = x;
cout<< "object constructed" << "\n";
}
Test(const Test& t)
{
a = t.a;
cout<< "object copied" << "\n";
}
~Test()
{
a = 0;
cout<< "object destroyed" << "\n";
}
};
int main()
{
cout<< ((Test)10).a << "\n"; //1: object constructed, 2: 10, 3: object destroyed
cout<< "end";
_getch();
}
Output:
object constructed
10
object destroyed
end
(Test)10 is a temporay. it is trying to find an opertunity to be destoyed. we see that it is destroyed before cout<< "end"
.
second essential property of temporaries: a temporary tries not to call copy constaructor if possible:
example:
#include <conio.h>
#include <iostream>
using namespace std;
class A
{
public:
int a;
A(int x)
{
cout<< "constructor" "\n";
a = x;
}
A(const A& a)
{
cout<< "copy constructor" "\n";
this -> a = a.a;
}
};
void f(A a)
{
cout<< a.a << "\n";
}
A g()
{
return A(20);
}
int main()
{
f(g());
_getch();
}
Output:
constructor
20
in this example copy constructor must be call at least 2 times. but it is not called at all because A(20) and g() are temporaries.
third essential property of temporaries: in most compilers (inluding Dev C++) a reference to a temporary must be constant, & such reference prevents the temporary to be destroyed until the end of the block execution.
example:
#include <conio.h>
#include <iostream>
using namespace std;
class A
{
public:
int a;
A(int x)
{
a = x;
}
~A()
{
cout<< "destructor" "\n";
}
};
A f()
{
A a(10);
return a;
} // 1: destrcutor
int main()
{
{
const A& a = f();
cout<< "end" "\n"; // 2: end
} // 3: destructor
_getch();
}
output:
destructor
end
destructor
if you write: A& a = f();
instead of const A& a = f();
VC++ has no problem with it but Dev C++ refuses to compile.
now "temporary" is not a standard name, I defined it myself. I wanted to know if there's a standard name & if there' more info somewhere on the web?
the books about C++ say nothing about temporaries. experts in other forums said that there are conditions under which copy constructor is not called but they didn't say anything about temporaries & its main name if any..