A temporary object is an unknown object. If it appears outside the programmer's expectation (for example, any pass by value operation will lead to the copy operation, thus forming a temporary object), it will often cause a burden on efficiency. However, sometimes it is time to deliberately create some temporary objects, but it is also a skill to make the program clean and refreshing. Deliberately creating a temporary object is to add a pair of parentheses after the type name and specify the initial values, such as shape () or int (8 ), it is equivalent to calling the corresponding constructor without specifying the object name. STL most often applies this technique to the combination of functions and algorithms. For example:
# Include <iostream> # include <vector> # include <algorithm> using namespace STD; Template <typename T> class print {public: void operator () (const T & ELEM) {cout <ELEM <"" ;}}; int main () {int Ia [6] = {0, 1, 2, 3, 4, 5}; vector <int> IV (IA, IA + 6); // print <int> () is a temporary object, not a function call operation for_each (IV. begin (), IV. end (), print <int> ());}
Running result:
The last row is a temporary object that generates the print <int> "class template materialized", which will be passed into for_each. When for_each () ends, this temporary object ends its life.
STL-generation and application of temporary objects