Detailed description of C ++ reference -- takes you into the reference world

Source: Internet
Author: User

Original article links: http://blog.csdn.net/u011421608/article/details/30750355

1. Introduction

 

First, let's talk about the reference. You can remember that the reference is an alias. For example, Mr. Wang has a nickname called puppy. His mother calls the puppy to go home for dinner, that is, he calls Mr. Wang to go home for dinner.

Next we will use two lines of code to declare a reference (let's take Xiao Wang and the puppy for example ):

Int xiaoW;

Int & xiaoG = xiaoW;

The above is a reference to illustrate the following points:

1. & the operator is referenced instead of an address operator;

2. xiaoG is the alias of xiaoW, so the values and addresses of these two variables are the same;

3. The reference can only be initialized, but cannot be declared first and then assigned a value, because the reference is equivalent to a constant;

4. You must initialize a reference at the same time.

The reference is very loyal. If you define a variable alias, this alias will always belong to this variable, and its address will always be the same as the variable address, changing the alias value also changes the value of this variable.

Similarly, object references are the same as variables, but you must note that you cannot reference classes because classes are of a type and do not have a memory address.

The introduction to references is here. Let's take a look at the usage of references.

 

2. Comparison of three parameter passing Methods

 

There are three methods for passing parameters in a function: passing by value, passing by address, and passing by alias (passing by alias is also passing by address, here I will list it for convenience ). Next we will use three programs to compare the three methods. The function of the program is to exchange the values of two variables.

 

1. Pass by value.

# Include

 

Using namespace std;

 

Void swap (int I, int j)

{

Cout <"I before exchange:" <

Int temp;

Temp = I;

I = j;

J = temp;

Cout <"Switched I:" <

}

 

Int main ()

{

Int a = 1, B = 2;

Cout <"a before exchange:" <

Swap (a, B );

Cout <"a after exchange:" <

Return 0;

}

The program runs as follows:

 

From the results, we can see that the values of variables a and B are transmitted to I and j respectively. The values of I and j in the function are exchanged, but the values of a and B are not exchanged, what is the problem.

This is because when the values of a and B are passed to the function, this transfer mode is passed by value. The compiler will automatically create copies of a and B in the stack, then, the replicas of a and B are passed to the function. In this way, the replicas of a and B are exchanged in the function, instead of a and B. To solve this problem, we need to introduce pointers.

 

2. Pass by address.

# Include

 

Using namespace std;

 

Void swap (int * I, int * j)

{

Cout <"I before exchange:" <* I <"" <"j:" <* j <

Int temp;

Temp = * I;

* I = * j;

* J = temp;

Cout <"Switched I:" <* I <"" <"j:" <* j <

}

 

Int main ()

{

Int a = 1, B = 2;

Cout <"a before exchange:" <

Swap (& a, & B );

Cout <"a after exchange:" <

Return 0;

}

The program runs as follows:

 

As you can see, the values of a and B can be exchanged. Because the program passes the addresses of a and B, you can directly access a and B through the addresses in the function, exchange their values.

Although the pointer can implement the exchange function, it is troublesome to use and not easy to read. It looks much more intuitive to use the reference.

 

3. Pass by alias

# Include

 

Using namespace std;

 

Void swap (int & I, int & j)

{

Cout <"I before exchange:" <

Int temp;

Temp = I;

I = j;

J = temp;

Cout <"Switched I:" <

}

 

Int main ()

{

Int a = 1, B = 2;

Cout <"a before exchange:" <

Swap (a, B );

Cout <"a after exchange:" <

Return 0;

}

The program runs as follows:

 

The result is also a successful exchange, the program looks easy to understand, and the operation is quite convenient.

 

Iii. Transfer objects

 

Objects and variables can be passed as parameters. what is different is that an object may contain a large amount of data. What is the way in which objects are transmitted in the preceding three methods.

 

1. Pass objects by value

When a parameter passed by value is an object, the compiler will also create a copy of the object. when an object is returned in a function, a copy of the object will also be created, when the object has a lot of data, the memory consumption is very large. Let's look at the program passed by value first.

# Include

 

Using namespace std;

 

Class

{

Public:

A () {cout <"constructor called \ n" <

A (A & a) {cout <"copy constructor called \ n" <

~ A () {cout <"destructor called \ n" <

Private:

Int x;

};

 

A func (A)

{

Return;

}

 

Int main ()

{

A;

Func ();

Return 0;

}

The program running result is as follows:

 

 

The program running result shows that the constructor is executed once, the constructor is copied twice, and the constructor is parsed three times. Next, we will analyze the results and code of the Program (this knowledge is very important to the novice, remember !), The main function creates an object a, so it calls the constructor and passes a to the func function. In this case, the copy constructor is automatically called to create a copy of object, that is to say, the copy passed to the func function is the copy of a instead of a itself. The return value of the func function is the object, and the return method is the return value. At this time, the copy constructor is automatically called to create a copy of the return value, so we can see that the constructor is called once and the constructor is copied twice, and the three constructor is also called to release the memory.

 

2. Transfer objects by address

The program results of passing objects by value show that the system overhead of this method is very large, and passing by address solves this problem.

 

# Include

 

Using namespace std;

 

Class

{

Public:

A () {cout <"constructor called \ n" <

A (A & a) {cout <"copy constructor called \ n" <

~ A () {cout <"destructor called \ n" <

Private:

Int x;

};

 

A func (A *)

{

Return *;

}

 

Int main ()

{

A;

Func (& );

Return 0;

}

The program running result is as follows:

 

It can be seen that the above program avoids calling the constructor twice, because the address is passed when the object a is passed to the func function, and the return address of the func function is also an address.

 

3. Passing objects by alias

# Include

 

Using namespace std;

 

Class

{

Public:

A () {cout <"constructor called \ n" <

A (A & a) {cout <"copy constructor called \ n" <

~ A () {cout <"destructor called \ n" <

Private:

Int x;

};

 

A & func (A &)

{

Return;

}

 

Int main ()

{

A;

Func ();

Return 0;

}

The program running result is as follows:

 

It can be seen that passing objects by alias has the same effect as passing by pointer, And the implementation is much simpler. Here we will give a small note to new friends, that is, the type returned by the func function is an alias, if you want to receive this alias in the main function, you must also receive the data of the reference type, such as A & aa = func (a), instead of A Class A object, note This.

 

4. whether to use a pointer or reference

 

Since the reference can implement the pointer function and it is more convenient to use the pointer, is it possible to only use the reference function? The answer is no, because some function references of the pointer cannot be implemented, let's talk about the difference between reference and pointer.

1. the pointer can be null, but the reference cannot be null;

2. pointers can be assigned values, but references cannot be changed;

3. When creating a memory area in the heap, you must use a pointer to point to this area. Otherwise, it cannot be accessed and cannot be referenced to point

 

5. Exercise caution when using references.

 

The reference cannot be blank. Otherwise, the correct result cannot be obtained. Let's use the following program to feel it.

# Include

 

Using namespace std;

 

Class

{

Public:

A (int I) {x = I ;}

Int get () {return j ;}

Private:

Int j;

};

 

A & func ()

{

A a (100 );

Return;

}

 

Int main ()

{

A & aa = func ();

Cout <

Return 0;

}

The program running result is as follows:

 

We can see from the running results that we didn't get the correct j value (100). Why? The reason is that a in func is a local object. After the func function runs, a does not exist. Therefore, the func function returns an alias for an object that does not exist. Therefore, the value of j cannot be obtained correctly. It is easy to solve this problem, you only need to change the return value of the reference type of the func function to the type, and the correct result can be obtained, because a copy of object A will be created.

 

6. Message

 

When I first started to learn C ++, I had a special headache with references. However, as long as I had a clear understanding of how it works, it was still relatively simple to learn, so I wrote this blog with my own experience for the reference of beginners. Of course, the referenced knowledge is confusing and easily confused with pointers. You need to gradually master it in the application process. Therefore, we recommend that you read more and write more code. I wish all my friends can learn enough knowledge and make progress in practice to become a qualified Internet talent.

As I am just getting started, it is inevitable that you will miss out. Please forgive me. If you have any comments or suggestions on this article, please contact me via qq. Thank you!


Yuan

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.