C++
  Home arrow C++ arrow Page 5 - Temporary Variables: Procrastination is th...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

Temporary Variables: Procrastination is the Thief of Time
By: J. Nakamura
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 3
    2005-09-19

    Table of Contents:
  • Temporary Variables: Procrastination is the Thief of Time
  • Temporary Object Terminology
  • More than just a call
  • To return or not to return an object
  • Visualizing the unseen object
  • Back to the closest Enemy

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Temporary Variables: Procrastination is the Thief of Time - Visualizing the unseen object


    (Page 5 of 6 )

    There is a simple way to find out how the compiler performs these tricks: just print the different stages it goes through when dealing with our object. Another way would be to step through the code with a debugger while the application is running, but there is nothing wrong with using print statements (Brian Kernighan prefers them over the use of a debugger still [Kernighan] :).

    #include <stdio.h>
    class MyClass {
     char const *mName;
    public:
     MyClass(char const *name) : mName(name) {
      (void)printf(“%s – Constructor called.\n”, mName);
     }

     MyClass(MyClass const &other) : mName(“unseen object”) {
     (void)printf(“%s – Copy Constructor called.\n”, mName);
    }

    ~MyClass() {
     (void)printf(“%s – Destructor called.\n”, mName);
    }

    MyClass& operator=(MyClass const &rhs) {
     (void)printf(“%s – Assignment Op. called.\n”, mName);
    }
    };

    MyClass foo() {
     MyClass obj(“foo”);
     return obj;
    }

    Now we can see what happens when we assign the result of foo to an object MyClass we have instantiated ourselves:

    (void)printf(“\n-- test1 --\n”);
    MyClass obj(“myObject”);
    obj = foo();

    Here is the description of the work done:

    -- test1 --
    myObject - Constructor called.
    foo - Constructor called.
    unseen object - Copy Constructor called.
    foo - Destructor called.
    myObject - Assignment Operator called.
    unseen object - Destructor called.

    The constructor of ‘myObject’ and ‘foo’ was called as expected, but there is also an ‘unseen object’ being created when foo() returns. This is the temporary object (‘unseen object’) that is needed to make the data of the ‘fooobject’  survive beyond the scope of the function call.

    The result data stored the temporary object is copied into ‘myObject’ using its assignment operator, after which the temporary is destroyed.

    Two extra objects were created to provide one object with data! That is quite a lot; all we wanted was to have some data survive beyond the scope of the function call. Wouldn’t it be nice if we could get rid of that temporary object?

    It is very simple to let data survive beyond the scope of the function call when that data already exists outside the function. Instead of returning an object by value, we can return a reference or pointer to it. These refer to the object by address, and returning/copying addresses is much cheaper.

    We have to make a small adaptation to the example to make sure that the ‘foo’ object exists outside of the function scope. Nasty things would happen if we were to return a reference to a local object that is destructed before we can use the reference!

    In the function we can make the object static to the function, and let the function return a reference to this static object, so we can circumvent this problem.

    MyClass& foo2() {
     static MyClass obj(“foo2”);
     return obj;
    }

    Then we rerun our test:

    (void)printf(“\n-- test2 --\n”);
    MyClass obj(“myObject”);
    obj = foo2();

    Ah good! We got rid of the temporary object, which is exactly what we wanted to do because we are returning the address (reference) to a static object that exists outside the function:

    -- test2 --
    myObject - Constructor called.
    foo2 - Constructor called.
    myObject - Assignment Operator called.

    Note that the foo2 constructor is only called the first time you call the foo function. This is an additional benefit that objects static to a function offer you: they are only constructed the first time you call the function. The Meyers Singleton [Meyers] uses this fact to help you prevent a (possibly expensive) construction, because when the function is never called, the object will not be created.

    More C++ Articles
    More By J. Nakamura


     

    C++ ARTICLES

    - Paths and Files
    - Directories in C++
    - Focusing on C++ Files
    - Const Correctness in C++
    - Manipulating Streams and Files with C++
    - Streams and Files
    - Multiplying Large Numbers with Karatsuba`s A...
    - Large Numbers
    - Dijkstra`s Shunting Algorithm with STL and C...
    - Brief Introduction to the STL Containers
    - The Standard Template Library
    - Templates in C++
    - C++ Programmer Alerts
    - C++ Programming Tips
    - First Steps in (C) Programming, conclusion






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT