Is it more efficient to call operator+= to define operator+ than other methods?

Source: Internet
Author: User

Title, the implementation of operator+= and operator+ is given below.

1sales_data&2Sales_data::operator+=(ConstSales_data &RHS)3 {4Units_sold + =Rhs.units_sold;5Revenue + =rhs.revenue;6     return* This;7 }8 9 Sales_dataTen operator+(ConstSales_data &LHS,ConstSales_data &RHS) One { ASales_data sum = LHS;
-sum + = RHS; - returnsum; the}

The code above is called operator+ to define the operator+=.

First operator+ has two parameters whose parameter type is const and is not required to be changed, and its return type is a copy of the Sales_data type. But each time you need to define a temporary variable in the function body to return the copy.

operator+= has a parameter whose parameter type is const and does not need to be changed, and its return type is a reference of type Sales_data. Each time you do not need to create a temporary variable within the function, you can return *this directly.

If you use operator+ to define operator+=, a sales_data temporary variable is created each time, whether you call operator+ or operator+=.

Therefore, it is more efficient to call operstor+= to define operator+.

You will also find this problem helpful to you:

Http://stackoverflow.com/questions/21071167/why-is-it-more-efficient-to-define-operator-to-call-operator-rather-than-the

Calling operator+= to define operator+ is more efficient than other methods?

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.