STL-generation and application of temporary objects

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.