devxlogo

Temporay Class Objects

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist