Detailed description of C ++ value transfer, pointer transfer, and reference Transfer

Source: Internet
Author: User

Recently I have written several in-depth discussions about arrays and pointers.ArticleIn C language, all non-array parameters are passed as values"

Behind arrays and Pointers-memory angle Semantics "traps"-arrays and pointers

There are still some misunderstandings about value passing, pointer passing, and reference passing. I think it is necessary to explain it here ~

The following is an example to describe in detail.

Value transfer:

The form parameter is a copy of the real parameter. Changing the value of the form parameter does not affect the value of the external real parameter. From the perspective of the called function, value passing is unidirectional (real parameter-> parameter), and parameter values can only be passed in,

Cannot be transferred out. When the function needs to modify parameters internally and does not want this change to affect the caller, the value is passed.

Pointer transmission:

The parameter is a pointer to the real parameter address. When a parameter is directed to an operation, it is equivalent to an operation on the real parameter itself.

Reference transfer:

The parameter is equivalent to the "alias" of the real parameter. The operation on the parameter is actually an operation on the real parameter. During the reference transfer process, the form parameter of the called function is also used as a local variable on the stack.

The memory space is opened up, but the address of the real variable is stored by the main function. Any operation of the called function on the form parameter is processed as indirect addressing.

The address stored in the stack accesses the real variable in the main function. Because of this, any operation performed by the called function on the form parameter affects the real parameter variables in the main function.

 

Theoretically speaking,

The followingCodeThis is explained in detail (the essence of the problem is explained from the perspective of the real parameter and the storage address of the form parameter in the memory, which is easy to understand)

 1 # Include <iostream>
2 Using Namespace STD;
3 // Value Transfer
4 Void Change1 ( Int N ){
5 Cout < " Value Transfer-function operation address " <& N <Endl; // The copied address instead of the source address is displayed.
6 N ++;
7 }
8
9 // Reference Transfer
10 Void Change2 ( Int & N ){
11 Cout < " Reference transfer-function operation address " <& N <Endl;
12 N ++;
13 }
14 // Pointer Transmission
15 Void Change3 ( Int * N ){
Cout < <span>"</span> Pointer transfer-function operation address " <N <Endl; <br>
* N = * n + <span>1</span> ; <br>
} <br>
Int Main (){ <br>
Int N = <span>10</span> ; <br>
Cout < <span>"</span> Real parameter address " <& N <Endl; <br>
Change1 (N ); <br>
23 Cout < " After Change1 () n = " <N <Endl;
24 Change2 (N );
25 Cout < " After Change2 () n = " <N <Endl;
26 Change3 (& N );
27 Cout < " After Change3 () n = " <N <Endl;
28 Return True ;
29 }

The running result is as follows (different machines may be different)

The real parameter address is 0x22ff44.

When the value is passed, the address of the function operation is 0x22ff20 and not the real parameter itself. Therefore, the value of the real parameter cannot be changed when the function operation is performed.

Let's look at the reference transfer. The operation address is the real parameter address, which is just an alias of the real parameter. The operation on it is the operation on the real parameter.

The next step is Pointer transmission. You can also find that the Operation address is a real parameter address.

So, what is the difference between reference transfer and pointer transfer?

Reference rules:
(1) The reference must be initialized at the same time (the pointer can be initialized at any time ).

(2) there cannot be a null reference, and the reference must be associated with a valid storage unit (the pointer can be null ).
(3) once the reference is initialized, the reference relationship cannot be changed (the pointer can change the object at any time ).

Essence of pointer transmission:

A pointer passing parameter is essentially a value passing method, which transmits an address value. During value transfer, parameters in the form of called functions are processed as local variables of the called functions,

That is, the memory space is opened in the stack to store the values of the real parameters put in by the main function, thus becoming a copy of the real parameters. The feature of value passing is the form parameter of the called function pair

Any operation is performed as a local variable and does not affect the value of the real variable of the main function..(The address value of the real parameter pointer will not change here)Skip this section if you cannot understand it.

Pointer passing and reference passing are generally applicable:

Modify parameters in the function and modify the parameters to affect the caller. The comparison pointer/reference transfer can be used to pass the changes from the form parameter to the real parameter (in fact, it is directly modified on the memory of the real parameter,

Unlike passing values to copy the values of real parameters to another memory address ).

Another usage is: when a function actually needs to return multiple values, but only one value can be explicitly returned, other variables that need to be returned can be passed through pointers/references.

To the function, after the function is modified and returned, the caller can get the modified variable, which is also equivalent to passing an implicit return value.

 

 

The following is a good article on pointers and references. For more information, see the source address of the original article.: Http://xinklabi.iteye.com/blog/653643

In terms of concept. Essentially, a pointer is a variable that stores the variable address. It is logically independent and can be changed, this includes changes to the address it points to and the data stored in the address it points.

Reference is an alias. It is not logically independent and its existence is dependent. Therefore, the reference must be initialized at the beginning, in addition, the referenced object cannot be changed throughout its lifecycle (it can only be attached to the same variable from start to end ).

InC ++In, pointers and references are often used to pass function parameters. However, pointer passing parameters and reference passing parameters are essentially different:

A pointer passing parameter is essentially a value passing method, which transmits an address value. During the value transfer process, parameters in the form of the called function are processed as local variables of the called function, that is, the memory space is opened in the stack to store the values of the real parameters put in by the main function, it becomes a copy of the real parameter. The feature of value transfer is that any operation of the form parameter by the called function is performed as a local variable, without affecting the value of the real parameter variable of the main function.. (The address value of the real parameter pointer will not change here)

During the reference transfer process, the form parameters of the called functions, although also opened up the memory space in the stack as local variables, however, the address of the Real Variable put in by the main function is stored. Any operation of the called function on the form parameter is processed as indirect addressing. That is, the address stored in the stack is used to access the real variable in the main function. Because of this, any operation performed by the called function on the form parameter affects the real parameter variables in the main function.

Reference transfer and pointer transfer are different, although they are all a local variable in the space of the called function stack, however, any processing of referenced parameters will operate the relevant variables in the main function in an indirect addressing method. If you change the pointer address in the called function for pointer passing parameters, it will not affect the variables related to the main function. If you want to change the relevant variables in the main function by passing the pointer parameter, you must use a pointer to the pointer or pointer reference.

To further deepen the differences between pointers and references, I will explain the differences between them from the compilation perspective:

ProgramDuring compilation, the pointer and reference are respectively added to the symbol table. The symbol table records the variable name and the address corresponding to the variable. The address value corresponding to the pointer variable in the symbol table is the address value of the pointer variable, and the address value referenced in the symbol table is the address value of the referenced object. The symbol table will not be changed after it is generated, so the pointer can change the object to which it points (the value in the pointer variable can be changed), but the referenced object cannot be modified.

Finally, we will summarize the similarities and differences between pointers and references:

★Similarities:

● All are addresses;

The Pointer Points to a piece of memory. Its content refers to the memory address, and the reference is the alias of a piece of memory.

★Differences:

● A pointer is an entity, and a reference is only an alias;

● The reference can only be initialized once during definition, but cannot be changed afterwards; the pointer can be changed; the reference can be "from one end", and the pointer can be "Thinking Differently ";

● No referenceConst, Pointer hasConst,ConstThe pointer of is immutable ;(Specifically, there is no form like Int & Const A, while const Int & A does. The former is used as a guideline, that is, the alias cannot be changed. This is of course, so this form is not needed, the value indicated by the latter Guide cannot be changed.)

● The reference cannot be blank or the pointer can be blank;

●"SizeofReference "to get the variable pointed(Object)And"SizeofPointer "gets the pointer size;

● Auto-increment of pointer and reference(++)Different computing meanings;

● The reference is type-safe, but the pointer is not(References have more type checks than pointers)

I. Concepts of reference

Reference introduces a synonym for an object. The expression of the definition reference is similar to the definition pointer, but it is replaced *.
For example, point pt1 ( 10 , 10 );
Point & pt2 = pt1; defines a reference where pt2 is pt1. With this definition, pt1 and pt2 indicate the same object.
It is important to note that references do not generate copies of objects, but are only synonyms of objects. Therefore, after the current statement is executed:
Pt1.offset (2 , 2 );
Both pt1 and pt2 have ( 12 , 12 .
The reference must be initialized immediately during definition because it must be a synonym for something. You cannot define a reference before
Initialize it. For example, the following statement is invalid:
Point & pt3;
Pt3 = pt1;
So what is the purpose of referencing a synonym for something?
The following two main purposes of reference are discussed: as a function parameter and return the left value from the function.

Ii. Reference parameters

1 Passing variable parameters
In traditional C, parameters are passed through values when a function is called, which means that the function parameters do not have the ability to return values.
Therefore, in traditional C, if function parameters are required to have the ability to return values, they are usually implemented through pointers. For example
The C program for the exchange of two integer values is as follows:
Void Swapint (Int *, Int * B)
{
Int Temp;
Temp = *;
A = * B;
* B = temp;
}

After the reference mechanism is used, the C ++ version of the above program is:
Void Swapint ( Int &, Int & B)
{
Int Temp;
Temp =;
A = B;
B = temp;
}
The C ++ method that calls this function is: swapint (x, y); C ++ automatically transmits the address of X and Y to the swapint function as a parameter.

2 , To pass a large object to the Function
When a large object is passed to a function, the parameter transfer efficiency can be improved by using reference parameters, because reference does not produce
Copy, that is, when the parameter is passed, the object does not need to be copied. The following example defines a class with a finite Integer Set:
Const Maxcard = 100 ;
Class Set
{
Int Elems [maxcard]; // And maxcard indicates the maximum number of elements in the set.
Int Card; // Number of elements in the collection.
Public :
Set () {card = 0 ;} // Constructor
Friend set Operator * (Set, set ); // Overload operator number *, used to calculate the intersection of a set, using an object as a value passing Parameter
// Friend set operator * (set &, set &) Heavy-duty operator number *, used to calculate the intersection of sets and use the object reference as the value passing Parameter
...
}
First consider the implementation of set intersection
Set Operator * (Set set1, set set2)
{
Set res;
For ( Int I = 0 ; I <set1.card; ++ I)
For ( Int J = 0 ; J> set2.card; ++ J)
If (Set1.elems [I] = set2.elems [J])
{
Res. elems [res. Card ++] = set1.elems [I];
Break ;
}
Return Res;
}
Since the overload operator cannot operate the pointer independently, we must declare the number of operations as the set type rather than set *.
When * is used for intersection operations, the entire set is copied, which is very inefficient. We can use references to avoid this situation.
Set Operator * (Set & set1, set & set2)
{Set res;
For ( Int I = 0 ; I <set1.card; ++ I)
For ( Int J =0 ; J> set2.card; ++ J)
If (Set1.elems [I] = set2.elems [J])
{
Res. elems [res. Card ++] = set1.elems [I];
Break ;
}
Return Res;
}

Iii. Reference return values

If a function returns a reference, the function call can also be assigned a value. Here is a function that has two reference parameters and returns a double-precision reference:
Double & MAX ( Double & D1, Double & D2)
{
Return D1> D2? D1: D2;
}
Because the max () function returns a reference to the Double Precision number, we can use max () to add 1 to the large double precision number:
Max (x, y) + = 1.0 ;

 

If there is reprint please indicate the source: http://www.cnblogs.com/yanlingyin/

A fish @ blog

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.