Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Mar 31, 2000

Temporay Class Objects

Question:
Would you please tell me the difference between regular class objects and temporary class objects?

Answer:
The compiler creates temporary objects in several occasions. Usually, the temporary stores the result of a subexpression that is immediatley used the subexpression has been evaluated. For example, in the following expression,

  string  x, y, z;
  x=y+z;
the result of the subexpression x+z must be stored somewhere so that the compiler can use it to perform the assignment. Therefore, the compiler creates a temporary string objects that holds the result of the subexpression and then it assigns that temporary string to x. The temporary is destructed immediately after the assignment takes place. In other words, the compiler conceptually transforms the original expression x=y+z; into something like this:
  string _temp = y+z; // store result in a temp
  x = _temp; // assign temporary to x
  _temp.~string(); // destroy temporary
A temporary is also generated when you pass an object by value to a function, or when you return an object by value from a function.

You can explicitly create a temporary object by invoking the class's constructor. For example:
  void f(string s);
  int main()
  {
   f (string()); // create a temp and pass it to f
  }
Unlike ordinary objects, temporaries don't have names. Therefore, you can't access them directly.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date