Tuesday 29 November 2011

How and When are Temporaries generated

Understanding Temporaries

Temporaries are 1 of the main bottlenecks in creating high speed and efficient software.
so their understanding is very important.

A temporary as the name suggests is a hidden object that the compiler creates itself in order to achive something.Its done implicitly by the compiler without the knowledge of the programmer.
Main reasons for compilers such behavior is
1.TYPE MISMATCH
2.PASSING BY VALUE
3.RETURNING BY VALUE

1.Type mismatch
for eg:
class A
{
int var;
public:
A(int x)
{
var = x;
}
void func(A);
};

Now here is a constructor for A which takes an integer argument...!!
So now dese r d ways in which we can create objects for A
A a(10); \\Normal nthng unusual
A a = 10; \\Hey wats happening here
a.func(10); \\Hey wats happening here
So wats happening in these two lines...??
actually the compiler was expecting an object of A as function argument and on RHS..
but instead it got an "int"....But wait these lines still runs and the compiler doesnt complain. This shows that compiler is very generous and is helping us underneath.
Actually the compiler knows that an object of can be created if it has an integer argument, SO
it creates a TEMPORARY.....!!
A temp(10); //Constructor called
a = temp; //Copy constructor called
~temp; //Destructor called
So u see just to create a TEMPORARY
2 constructors and 1 destructor is called...u will say so what
when we do
int = int + int...no 1 complained for this so far
but listen guys temporaries are not significant for primitive data types but for user defined object of size 100 bytes IT IS SIGNIFICANT.
So A = A + A; vil also create a temporary if '+' operator is overloaded.
a way to overcome dis is use += unary operator.
A obj,obj1,obj2;
for obj = obj1 + obj2; \\Temporary here
but obj = obj1 \\No Temporary
obj += obj2 \\No Temporary here as well

Also Remember passing by value and returning by value also creates a TEMPOARAY. As a local copy is always created.
So always try to pass pointers or better References.

And these constructors are called "Converting Constructors"
To prevent this we should use "Explicit constructors"
explicit A(int)
now it wont create a temporary :)

No comments:

Post a Comment