devxlogo

When an explicit creation of a temporary object is useful

When an explicit creation of a temporary object is useful

If you need an object serving only as a function argument, you can use an explicit constructor call to instantiate a nameless object rather than a named one:

 void putPixel(const point& location);main() {		PutPixel(  point(100, 100) /*create a temporary point object as an argument*/ );}

In the example above, a temporary object is preferred since it’s automatically destroyed right after it’s use and there is no danger that it will be mistakenly used elsewhere in the program . One more benefit is a potential optimization: the compiler can suppress the construction and destruction of the temporary object by inline substitution.

devx-admin

Share the Post: