Differences Between Reference transfer and pointer transfer in C ++

Source: Internet
Author: User

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 ).

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

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 of 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:

During compilation, the program adds pointers and references to the symbol table, respectively. 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 const is referenced, the pointer has const, And the pointer of const is immutable; (specifically, no Int &
Const A is in this form, while const Int & A is in this form. The former guides the use of itself, 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;

● "Sizeof reference" gets the size of the variable (object) pointed to, while "sizeof Pointer" gets the size of the pointer;

● Pointer and reference auto-increment (++) operations have different meanings;

● The reference is type-safe, but the pointer is not (the reference has more type checks than the pointer

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 *.
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) values.
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 * a, 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 & A, 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. Passing large objects to Functions
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]; // The element in the set. maxcard indicates the maximum number of elements in the set.
Int card; // The number of elements in the set.
Public:
Set () {card = 0;} // Constructor
Friend set operator * (set, set); // reload operator number *, used to calculate the intersection of a set, using an object as a value passing Parameter
// Friend set operator * (set &, set &) overload 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;

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.