Browse DevX
Sign up for e-mail newsletters from DevX

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Temporay Class Objects

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

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;
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.



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