Understanding-plus reload to use global function + return value non-reference

Source: Internet
Author: User

One, plus inC + + overloading a bit of using a global function is the ability to use cascading methods for addition operations.

Fraction a,b,c,d,e; A=b+c+d+e;

If the member function

1. The this pointer of the returned b is used for the following variables respectively, so it is a modification to b ;

2, if the return of a new variable, the above cascading problem seems to be resolved.

3, the problem is that if there is an implicit type conversion, and the first argument is a type that needs to be converted, you may not find the member function of the definition, so you can use a global approach to the problem

Second, the return value needs a value, not a reference

To return a reference from a local function, consider two scenarios.

1. If the local variable is applied on the stack, then when the function returns, the pointer is rolled back, which is when the other function executes again, the original value may be rewritten. The memory here is reused, resulting in an unknown nature.

Here is an example:

int& func () {    int m=9;    return m;} void Func2 () {    int i=1;    cout << "F2:" << i << Endl;} int main () {    int& fp=func ();    Func2 ();    cout<<fp<<endl;    return 0;} Output is:1

Apparently this caused a memory rewrite

Sometimes we write like this

int main () {    int fp=func ();    Func2 ();    cout<<fp<<endl;    return 0;}

This is the output or 9, because this is the FP is just a value, not a reference

2. If the value returned is requested on the heap

Fraction a,b,c,d,e;   A=b+c+d+e;

Then I will cause a memory leak here.

B+c Returns a new memory, but the pointer is lost after executing (b+c) +d , so the delete is not possible, andThe subsequent situation is similar.

Understanding-plus reload to use global function + return value non-reference

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.