"Reprint" C + + value passing, pointer passing, reference passing

Source: Internet
Author: User

Original link: http://www.cnblogs.com/yanlingyin/

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 namespacestd;3 //Value Passing4  voidChange1 (intN) {5cout<<"value passing--function action address"<<&n<<endl;//The copied address is displayed instead of the source address6n++;7 }8 9 //Reference DeliveryTen voidChange2 (int&N) { Onecout<<"reference Passing--function action address"<<&n<<Endl; An++; - } -  //Pointer passing the voidChange3 (int*N) { -cout<<"pointer passing--function operation address"<<n<<Endl; -*n=*n+1; -  }  + intMain () { -     intn=Ten; +cout<<"address of the actual parameter"<<&n<<Endl; A change1 (n); atcout<<"After change1 () n="<<n<<Endl; - change2 (n); -cout<<"After change2 () n="<<n<<Endl; -Change3 (&n); -cout<<"After change3 () n="<<n<<Endl; -     return true; in}
View Code

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.

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)

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.

One, the referenced concept reference introduces a synonym for the object. Defining a reference is similar to defining a pointer, just using the& instead of *. Example: Point pt1 (Ten,Ten); Point&pt2=pt1; Defines a reference pt2 to PT1. 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); pt1 and Pt2 both have ( A, A) value. A reference must be initialized as soon as it is defined, because it must be a synonym for something. You cannot initialize a reference until you define it first. For example, the following statement is illegal: point&PT3;PT3=pt1; So since the reference is just a synonym for something, what's the use of it? 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 parameters1, passing a mutable parameter in the traditional C, the function is passed by value when called, that is, the function's argument does 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, the C program that implements two integer variable value exchange is as follows:voidSwapint (int*a,int*b) {inttemp;temp=*A;a=*b;*b=temp;} After using the reference mechanism, the C of the above program++version is:voidSwapint (int&a,int&b) {inttemp;temp=A;a=b;b=temp;} Call the C of the functionThe + + method is: Swapint (x, y); C++automatically passes the address of X, y as an argument to the Swapint function. 2, passing a large object to a function when a large object is passed to a function, reference parameters can be used to improve the efficiency of the parameter passing, because the reference does not produce a copy of the object, that is, when the parameter is passed, the object does not need to be copied. The following example defines a class for a finite set of integers:Constmaxcard= -; Class Set {intElems[maxcard];//sets and elements in Maxcard that represent the maximum number of elements in the collection. intCard//the number of elements in the collection.  Public: Set () {card=0;}//constructor FunctionFriend Setoperator* (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...} First consider the implementation set of the set intersectionoperator*(set Set1,set Set2) {set res; for(intI=0; i<set1.card;++i) for(intj=0; j>set2.card;++j)if(set1.elems[i]==Set2.elems[j]) {Res.elems[res.card++]=Set1.elems[i]; Break;}returnRes;} Because overloaded operators cannot operate on pointers alone, we must declare the operands as set type instead of Set*. Per use*when you do the intersection operation, the entire collection is copied, which is inefficient. We can use references to avoid this situation. Setoperator* (Set &set1,set &Set2) {Set res; for(intI=0; i<set1.card;++i) for(intj=0; j>set2.card;++j)if(set1.elems[i]==Set2.elems[j]) {Res.elems[res.card++]=Set1.elems[i]; Break;}returnRes;} Iii. reference return value if a function returns a reference, the call to the 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&AMP;D1,Double&D2) {returnD1>d2?D1:d2;} Since the max () function returns a reference to the double precision number, we can use Max () to add 1:max (x, y) to the larger double+=1.0;

"Reprint" C + + value passing, pointer passing, reference passing

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.