C + + value passing, pointer passing, reference passing in a detailed

Source: Internet
Author: User

Tag: Operation returns TOR tool processing source Address object calling function res

Recently wrote several deep-seated articles on arrays and pointers, which referred to "C, where all non-array formal parameter passes are in value-passed form"

Semantic "traps"---arrays and pointers

There will be misunderstandings about value passing, pointer passing, and reference passing, all of which I feel necessary to explain here.

The following examples are explained in detail.

Value passing:

The parameter is a copy of the argument, and changing the value of the parameter does not affect the value of the external argument. From the point of view of the called function, the value pass is one-way (argument-and-parameter), the value of the argument can only be passed in,

cannot be outgoing. The value is passed when the parameter needs to be modified inside the function and you do not want the change to affect the caller.

Pointer passing:

The parameter is a pointer to the address of the actual parameter, which is equivalent to the operation of the argument itself when it points to the parameter

Reference delivery:

The formal parameter is equivalent to the "alias" of the argument, the operation of the formal parameter is actually the operation of the argument, in the process of reference passing, the parameters of the function are also used as local variables in the stack

The memory space is opened, but the address of the argument variable that is put in by the main function is stored. Any operation of a modulated function on a formal parameter is handled as an indirect addressing, i.e. by

The address stored in the stack accesses the argument variable in the keynote function. Because of this, any action taken by the modulated function on the parameter affects the argument variables in the keynote function.

The theory is not much to say,

The following code provides a detailed explanation of this (actual argument, the angle of the parameter in memory to address the nature of the problem, easy to understand)

1 #include <iostream>
2 using namespace Std;
3//Value Pass
4 void Change1 (int n) {
5 cout<< "value pass--function operation Address" <<&n<<endl;
6 n++;
7}

9//reference delivery
ten void Change2 (int & N) {
11
n++;
13}
//Pointer pass
void Change3 (int *n) {
16
*n=*n+1;
18
int Main () {
int n=10;
cout<< "Address of the argument" <<&n<<endl;
change1 (n);
cout<< "after Change1 () n=" <<n<<endl;
change2 (n);
cout<< "after Change2 () n=" <<n<<endl;
Change3 (&n);
cout<< "after Change3 () n=" <<n<<endl;
return true;
29}

The results of the operation are as follows (different machines may vary)

As you can see, the address of the argument is 0x22ff44

When a value is passed, the address of the function operation is 0x22ff20 not the argument itself, so manipulating it does not change the value of the argument

Again, the reference pass, the operation address is the actual parameter address, just equivalent to an alias of the argument, the operation of it is the operation of the argument

Next is the pointer pass, also can find the operation address is the address of the actual argument

So what's the difference between a reference pass and a pointer pass?

Rules to refer to:
(1) The reference is created and must be initialized (the pointer can be initialized at any time).

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

The essence of pointer passing:

A pointer pass parameter is essentially the way a value is passed, which is passed an address value. In the process of value passing, the formal parameters of the called function are treated as local variables of the modulated function,

That is, the memory space is opened in the stack to hold the value of the argument that is put in by the main function, thus becoming a copy of the argument. The characteristic of the value transfer is the function of the parameter

Any operation is performed as a local variable without affecting the value of the argument variable of the keynote function. (Here is the address value of the argument pointer itself will not change) if you can't understand it, you can skip the paragraph.

pointer passing and reference passing generally apply to :

The function internally modifies the parameters and wants the changes to affect the caller. Contrast pointer/reference passing can alter the change from the formal parameter "to" the argument (which is actually modified directly in the memory of the argument,

It is not modified to copy the value of the argument to another memory address as if the value was passed.

Another usage is that when a function actually needs to return multiple values, but only explicitly returns a value, you can pass the variable that needs to be returned as a pointer/reference

To the function, so that after the function is modified and returned, the caller can get the modified variable, also equivalent to an implicit return value of the pass bar.

Here is what I think about pointers and references written very good articles, you can refer to the original source address : http://xinklabi.iteye.com/blog/653643

Conceptually speaking. A pointer is essentially a variable that holds the address of a variable, logically independent, and can be changed, including the change in the address it points to and the data stored in the address it points to.

Whereas a reference is an alias, it is logically not independent, its existence is dependent, so the reference must be initialized at the outset, and the object it refers to cannot be changed throughout its life cycle (it can only be attached to the same variable from beginning to end).

In C + +, pointers and references are often used for parameter passing of functions, however, pointer passing parameters and reference passing parameters are inherently different:

A pointer pass parameter is essentially the way a value is passed, which is passed an address value. In the process of value passing, the formal parameters of the called function are treated as local variables of the modulated function, that is, the memory space is opened in the stack to hold the values of the arguments put in by the key function, thus becoming a copy of the argument. The characteristic of value passing is that any operation of the function on the formal parameter is done as a local variable, without affecting the value of the argument variable of the main key function. (Here is the address value of the argument pointer itself will not change)

In the process of reference passing, the formal parameters of the called function also open up the memory space in the stack as a local variable, but the address of the argument variable that is put in by the key function is stored. Any operation of the modulated function on the formal parameter is handled as an indirect addressing, that is, the argument variables in the central Melody function are accessed through the address stored in the stack. Because of this, any action taken by the modulated function on the parameter affects the argument variables in the keynote function.

Reference passing and pointer passing are different, although they are a local variable on the function stack space, but any handling of reference parameters is handled by an indirection to the relevant variables in the key function. For pointers passing parameters, if you change the address of the pointer in the called function, it will not affect the relevant variable of the key function. If you want to change the related variable in the key function by passing the pointer parameter, you have to use a pointer to the pointer, or a pointer reference.

To further deepen the distinction between pointers and references, let me elaborate on the differences between them from a compilation perspective:

The program adds pointers and references to the symbol table at compile time, and the symbol table records the variable name and the corresponding address of the variable. The corresponding address value of the pointer variable on the symbol table is the address value of the pointer variable, and the corresponding address value on the symbol table refers to the address value of the Reference object. The symbol table does not change after it is generated, so the pointer can change the object it points to (the value in the pointer variable can be changed), and the reference object cannot be modified.

Finally, summarize the same points and different points of pointers and references:

★ Same point:

Are the concept of addresses;

The pointer points to a piece of memory whose contents are the address of the referred memory, and the reference is the alias of a block of memory.

★ Different points:

The pointer is an entity, and the reference is only an individual name;

References can only be initialized once at the time of definition, immutable, pointers variable, reference "mindedness", pointers "inconstant";

The reference does not have a const, the pointer has a const,const pointer is immutable, (specifically, there is no int& const a This form, and the const int& A is some, the former guideline with itself that alias can not be changed, which is of course, so do not need this form, the latter The guideline cannot be changed by the value of the reference)

The reference cannot be null, the pointer can be empty;

The "sizeof reference" gets the size of the variable (object) pointed to, and the "sizeof pointer" gets the size of the pointer itself;

Pointer and reference self-increment (+ +) operation has different meanings;

References are type-safe, while pointers are not (references are more type-checked than pointers)

First, the concept of reference

The reference introduces a synonym for the object. Defining a reference is similar to defining a pointer, but using & instead of *.
Example: Point pt1 (10,10);
Point &pt2=pt1; A reference to PT1 is defined for pt2. With this definition, PT1 and pt2 represent the same object.
It is particularly emphasized that a reference does not produce a copy of the object, just a synonym for the object. Therefore, when the following statement executes:
Pt1.offset (2,2);
Both PT1 and pt2 have a value of (12,12).
A reference must be initialized as soon as it is defined, because it must be a synonym for something. You cannot define a reference before
Initialize it. For example, the following statement is illegal:
Point &pt3;
PT3=PT1;
So since the reference is just a synonym for something, what is its use?
The following is a discussion of the two main uses of a reference: as a function parameter and return an lvalue from a function.

Second, reference parameters

1. Passing Variable parameters
In traditional C, a function is passed by value when called, which means that the function's arguments do not have the ability to return a value.
So in the traditional C, if the function parameter has the ability to return a value, it is often implemented by pointers. For example, to implement
The C program for exchanging two integer variable values is as follows:
void Swapint (int *a,int *b)
{
int temp;
Temp=*a;
A=*b;
*b=temp;
}

After using the reference mechanism, the C + + version of the above program is:
void Swapint (int &a,int &b)
{
int temp;
Temp=a;
A=b;
B=temp;
}
The C + + method that calls the function is: Swapint (x, y); C + + automatically passes the address of X, y as an argument to the Swapint function.

2. Passing large objects to functions
When large objects are passed to a function, reference parameters can be used to improve the efficiency of parameter passing because the reference does not produce the object's
The copy, which is the parameter passing, does not need to be copied. The following example defines a class for a finite set of integers:
Const MAXCARD=100;
Class Set
{
int Elems[maxcard]; Sets and elements in Maxcard that represent the maximum number of elements in the collection.
int card; The number of elements in the collection.
Public
Set () {card=0;}//constructor
Friend set operator * (set, set); Overloaded operation symbol *, used to calculate the intersection of a set using an object as a pass-value parameter
Friend Set operator * (Set &, set &) overloaded operation symbol *, used to calculate the intersection of the set with the object's reference as a pass-value parameter
...
}
Consider the implementation of set intersection first
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;
}
Because overloaded operators cannot operate on pointers alone, we must declare the operands as set type instead of Set *.
The entire collection is duplicated every time the intersection is used, so it is 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;
}

Third, reference return value

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



If reproduced please specify the source: http://www.cnblogs.com/yanlingyin/

A Fish @ Blog Park

2011-12-7

C + + value passing, pointer passing, reference passing in a detailed

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.