If the return value of a function is an object, consider the efficiency of the Return Statement.

Source: Internet
Author: User

If the return value of a function is an object, the efficiency of the return statement should be considered. For example
Return string (S1 + S2 );
This is the syntax of a temporary object, indicating "Creating a temporary object and returning it ". Do not think it is different from "create first"
The result of a partial object temp and returning it is equivalent, as shown in figure
String temp (S1 + S2 );
Return temp;
OtherwiseCodeThree things will happen. First, the temp object is created and initialized.
Then the copy constructor copies temp to the external storage unit that saves the returned value. Finally, temp ends at the end of the function.
Is destroyed (calls the destructor ). However, the process of "Creating a temporary object and returning it" is different.
The interpreter directly creates and initializes temporary objects in an external storage unit, saving the copy and structure fee and improving
Efficiency.
Similarly, we do not want
Return int (x + y); // create a temporary variable and return it
Write
Int temp = x + y;
Return temp;
Because the internal data types such as int, float, and double do not have constructor or destructor
The variable syntax does not increase much efficiency,ProgramIt is more concise and easy to read.

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.