C + + cannot return a pointer or reference interpretation of a local object and a local variable

Source: Internet
Author: User

The writing of the calling function makes the program neat and easy to read when writing C + + code, but the return value of the calling function (the return value of the local variable, the variable, the struct, the array, etc.) is also a matter of note. A pointer or reference that returns a local variable is strictly forbidden in C + +.

In fact, the rules for returning values of functions are very well-written:

The return value of a function can be a pointer or reference to a numeric value and a global variable.

The return value of a function cannot be a local object or a pointer or reference to a local variable!!!

Reason:

The local variable that invokes the function is present in the stack, and the space of the local variable is freed after executing the calling function, that is, the local variable will not exist in memory after the call function executes. If a pointer to a local variable is returned or is a reference. Returned to the receiving object is the address of the local variable, and the resource of this address has been disposed, that is, the accepted return value will be null (because it was freed), error.

Add: A local variable returns a pointer or reference that is an address, and the return value is a number. (Different concepts)

C + + cannot return a pointer or reference interpretation of a local object and a local variable

Related Article

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.