C++ Design/Coding tips - Part 3
3. Temporary Objects

in

Temporary objects are created when:
-  Objects are returned from functions
-  Objects are given as arguments to functions

In these cases, constructor for the object is first invoked and later, destructor is invoked. So there will be some additional code and time consumed by the application. So, large temporary objects make for inefficient code, so try to minimize the number of temporary objects getting created. It can be achieved by using references rather than value.

In the code below, by calling InefficientWay(), we invoke constructer, destructor for the temporary object. But by calling EfficientWay(), we avoid it. And notice that, syntax of both functions is same.

class SomeClass
        {
        SomeClass()
        ...
        };

SomeClass InefficientWay ( SomeClass sclass )
        {
        return sclass;  
        }

SomeClass& EfficientWay ( const SomeClass& sclass )
        {
        return sclass;  
        }

int main ()
        {
        SomeClass obj1;
        obj1 = InefficientWay ( obj1 );
        obj1 = EfficientWay ( obj1 );

        return 0;
        }

Tutorial posted September 1st, 2005 by girishshetty categories [ ]

> C++ Design/Coding tips - Part 3

When you do this:

SomeClass obj1;

you declare an instance of the SomeClass class on the stack. And that is not a good idea. You should declare it a pointer, and in this case you won't have these problems.

> C++ Design/Coding tips - Part 3

>>When you do this:

>>SomeClass obj1;

>>you declare an instance of the SomeClass class on the stack. And that is not a good idea. You should declare it a pointer, and in this case you won't have these problems.

Valid point, but... some times we use stack variables rather than heap variable (where we should take care of deleting them). Assuming our stack variable is of small size, then its better to go for stack variable rather than heap variable.

Any how, I am discussing about avoiding temporary variables, not stack variables Vs Heap variables.

Regards Girish