Pass value and reference

Source: Internet
Author: User
Pass value and reference

In the commonly used text programming languages (C ++, Java, C #), the parameter passing method when calling subfunctions is mainly the reference passing method, that is, tell the called function where the parameter is located, not the parameter data. C ++ uses values for simple data transmission to maintain compatibility with the C language. However, for large data blocks, such as arrays, strings, structures, and classes, it is also transmitted in reference format.
The disadvantage of the value transfer method is obvious: each time you call a sub-function, you need to copy the data, which consumes a lot of memory. You do not need to copy data every time, saving the memory space and Data Replication time. However, it is not as secure to pass a reference directly, because the memory where the data is stored can be accessed by other functions during the transfer, which is not a problem in a single thread. However, with multiple threads, data security cannot be ensured.

 

Rules:

1. Replace the passed value with the passed reference to the const. In typical cases, it is more efficient and can avoid the disconnection problem (polymorphism is not possible ).

2. This rule does not apply to built-in types and iterators and function objects in STL. For them, passing values is usually more appropriate. Iterators and function objects in STL, because they are designed for passing values as a convention. The implementation of iterators and function objects has the responsibility to ensure efficient copying and not to be affected by the disconnection problem.

 

Reference knowledge points:

● Referenced variable. Define the format of an integer reference variable yi:
Int & yi = I; // variable I is an integer variable that has been defined
Meaning: yi is the alias of I. The two point to the same variable and are the two names of the same variable. No matter who modifies the variable, the variable will be modified.
Note: The referenced variable must be initialized before being initialized. It is different from Java.
● Reference parameters (reference and address transfer ). The format for defining referenced parameters is as follows:
The return type function name (parameter type & Parameter Name) {function body} is different from the non-reference parameter because the parameter name has an additional quote symbol "&".
Meaning: C ++ transmits values by default. That is to say, any modification to the form parameter in the function body does not affect the real parameter. Before the function is run, the copy constructor of the real parameter is called to generate a temporary variable, this temporary variable replaces the form parameter in the function body for calculation. This is why the values of the two variables cannot be exchanged through the function without reference or pointer, that is, when the copy constructor is called in C ++, if you want to modify the real parameter for efficiency, you must use the reference parameter, in this way, the real parameter itself is involved in the calculation of the function body.
  
● Return value of the reference type. The format for defining the reference return value is as follows:
Return type & function name (parameter type parameter name) {function body}
Meaning: Any temporary variables in the function must be destroyed after the function is run. If you want to return a variable, the copy constructor of the type to which the variable belongs will be called to construct a temporary variable to return, unless the referenced return value is used. Suppose there is a program in which class A has a function fun intended to return the object itself. Can we see it do this?
  
Run and print the following results:
Constructor
Copy Structure
Copy Structure
The program running result shows that the copy constructor has been called twice. Why? When the constructor is called twice: When "return * This;" is executed, the compiler will call the copy constructor when * this is the real parameter to construct the temporary variable, the other is to execute "A a1 =. fun (); ", the compiler calls the copy constructor when the temporary variable constructed in the preceding step is the real parameter A1 initialization. Change "a fun () {return * This;}" to "A & fun () {return * This;}", and then run the command to obtain the following result:
Constructor
Copy Structure
We can see that only one copy constructor is run during initialization of A1. the returned object is the object itself.
Note: The Return Value of the reference type is generally used to return the reference type parameters (for example, the output operator <in C ++) or the return object itself (for example, the overloaded value assignment operator ), you cannot return a reference to a temporary variable in the function. After the function is run, all the temporary variables must be destroyed. The object does not exist and the object itself cannot be returned [1].
Conclusion: The use of references in C ++ is complicated because of two reasons: first, in C ++, values are passed by default, instead of the address (for reference ), second, in C ++, variables created using different methods have different storage locations, different lifecycles, and different destruction methods and destruction responsibilities. Therefore, you must be very careful when using references in C ++. You must have a thorough understanding of references and use references in some aspects, such as copying constructors. Therefore, learning references is an important language basis for understanding the implementation of object-oriented mechanisms in C ++.

 

Note:

In the above example, my test result is

No matter whether the function fun returns a reference or not, the results are the same:

Constructor
Copy Structure
Although the results are the same, the trace code can find that the execution process is different.

When A reference is returned, fun does not call the copy constructor, but calls the constructor when a a1 = A. fun () is assigned a value.

When A non-reference is returned, return * this in fun directly calls the constructor, and in a a1 = A. fun (), no function is called here, so it is skipped directly...

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.