Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - The difference between reference and pointer in C++
The difference between reference and pointer in C++
★ Similarities:

1. Both are concepts of address;

The pointer points to a piece of memory whose content is the address of the memory; Reference is an alias for a memory block.

★ Difference:

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

2. You don't need to dereference (*) when using a reference, but the pointer needs to dereference;

3. A reference can only be initialized once when it is defined, and then it is immutable; The pointer is variable;

Quote "from one to the last"

4. The reference has no const, the pointer has const, and the pointer of const is immutable;

5. The reference cannot be empty, and the pointer can be empty;

6. "SizeofReference" obtains the size of the pointed variable (object), and "Sizeof pointer" obtains the size of the pointer itself (the address of the pointed variable or object);

typeid(T)= = typeid(T & amp; ) constant is true, sizeof (t) = = sizeof (t&; ) is always true, but when the reference is used as a member, it takes up the same space as the pointer (no standard regulations can be found).

7. Pointer and reference have different meanings of self-increasing (++) operation;

★ Contact person

1. The reference is implemented with pointers in the language (how? )。

2. For general applications, if you understand the reference as a pointer, you won't make serious semantic mistakes. Reference is a pointer with limited operations (only content extraction operations are allowed).

Reference is a concept in C++, and beginners can easily confuse reference with pointer. In the following procedure, n is a reference to m, and m is a reference.

int m;

int & ampn = m;

N is equivalent to an alias (nickname) of M. Any operation on N is an operation on M. For example, someone's name is Wang Xiaomao and his nickname is Sanmao. How to say "San Mao" is actually making irresponsible remarks about Wang Xiaomao. So n is neither a copy of M nor a pointer to M. In fact, n is M itself.

Some of the rules cited are as follows:

(1) References must be initialized when they are created (pointers can be initialized at any time).

(2) There can be no empty reference, and the reference must be associated with a legal storage unit (the pointer can be empty).

(3) Once the reference is initialized, the relationship of the reference cannot be changed (the pointer can change the object it points to at any time).

In the following example program, k is initialized as a reference to I, and the statement k = j does not change k to a reference to j, but changes the value of k to 6. Since k is a reference to I, the value of I also becomes 6.

int I = 5;

int j = 6;

int & ampk = I;

k = j; //The values of k and I both become 6;

The above program looks like playing a word game, and does not reflect the value of the quotation. The main function of reference is to pass parameters and return values of functions. In C++ language, there are three ways to transfer parameters and return values of functions: value transfer, pointer transfer and reference transfer.

The following is a sample program of "value passing". Since x in the Func 1 function body is a copy of the external variable n, changing the value of x will not affect n, so the value of n is still 0.

void Func 1(int x)

{

x = x+ 10;

}

int n = 0;

func 1(n);

cout & lt& lt" n = " & lt& ltn & lt& ltendl// n = 0

The following is an example program of "pointer passing". Because x in the Func2 function body is a pointer to the external variable n, changing the content of this pointer will change the value of n, so the value of n becomes 10.

void Func2(int *x)

{

(* x)=(* x)+ 10;

}

int n = 0;

func 2(& amp; n);

cout & lt& lt" n = " & lt& ltn & lt& ltendl// n = 10

The following is a sample program of "reference passing". Since x in the Func3 function body is a reference to the external variable n, x and n are the same thing. Changing x equals changing n, so the value of n becomes 10.

void func 3(int & amp; x)

{

x = x+ 10;

}

int n = 0;

func 3(n);

cout & lt& lt" n = " & lt& ltn & lt& ltendl// n = 10

Comparing the above three sample programs, we will find that the nature of "reference passing" is like "pointer passing" and the writing method is like "value passing". In fact, what "reference" can do, so can "pointer". Why "reference"?

This thing?

The answer is "Do the right job with the right tools".

Pointers can operate anything in memory without restriction. Although the pointer is powerful, it is very dangerous.

Just like a knife, it can be used for cutting trees, paper cutting, manicure, haircut and so on. Who dares to use it like this?

If you really only need to borrow an object's alias, use "reference" instead of "pointer" to avoid accidents. For example, if someone needs proof, just stamp the official seal on the document. You get him the key to the official seal, and he gets the rights he shouldn't have.

——————————

Excerpt from High Quality c++ Programming

Pointers and references are described in detail in more effective C++, and I will pass them on to you.

Clause 1: the difference between pointer and reference

Pointers and references look completely different (pointers use operators' *' and'->', and references use operators'.') but their functions seem to be the same. Pointers and references allow you to indirectly refer to other objects. How to decide when to use pointers and when to use references?

First of all, realize that under no circumstances can you use null references. References must always point to an object. So if you use a variable and point it to an object, but the variable may not point to any object at some time, you should declare the variable as a pointer, because then you can assign a null value to the variable. Conversely, if the variable explicitly points to an object, for example, your design does not allow the variable to be empty, then you can declare the variable as a reference.

"But, please wait a moment," you asked doubtfully. "What will happen to such code?"

char * PC = 0; //Set the pointer to null.

Char & amprc = * pc// Let the reference point to a null value.

This is very harmful, no doubt. The result will be uncertain (the compiler can produce some output, so anything can happen), and people who write such code should be avoided unless they agree to correct the mistakes. If you are worried that such code will appear in your software, then you'd better avoid using references completely or let a better programmer do it. We will ignore the possibility that references will point to null values in the future.

Because references must point to an object, in C, references should be initialized.

Chord and chord. RS; //Error, reference must be initialized.

String s ("xyzzy");

Chord and chord. RS = s; //correct, rs points to S.

Pointers are not so limited.

String * ps// uninitialized pointer

//legal but dangerous

The fact that there are no references to null values means that code that uses references is more efficient than code that uses pointers. Because you don't need to test the validity of a reference before using it.

Void printDouble (developed by constant double &)

{

cout & lt& ltrd; //There is no need to test rd, it

}//Definitely points to a double value.

Instead, you should always test pointers to prevent them from being empty:

Void printDouble (constant double *pd)

{

Intermediate frequency (pd)

{//Check if it is empty.

cout & lt& lt* pd

}

}

Another important difference between pointers and references is that pointers can be reassigned to point to different objects. However, the reference always points to the object specified at initialization and cannot be changed later.

The string s1("Nancy");

The string S2 ("Clancy");

Chord and chord. RS = s 1; // rs references s 1.

string * ps = & amps 1; // ps points to s 1.

Rs = s2// rs or s 1.

//But now the value of s 1

//"Clancy"

ps = & ampS2; // ps now points to S2;

// s 1 has not changed.

Generally speaking, you should use the pointer in the following situations: first, you should consider the possibility of not pointing to any object (in this case, you can set the pointer to be empty); Secondly, you need to be able to point to different objects at different times (in this case, you can change the direction of the pointer). If you always point to an object, once you point to an object, you won't change this point, then you should use a reference.

In another case, when an operator is overloaded, a reference should be used. The most common example is the operator []. The typical use of this operator is to return a target object, which can be assigned a value.

Vector & LTINT & GTV (10); //Establish a shaping vector with the size of 10;

//Vector is a template in the standard C library (see Article 35).

v[5]= 10; //The target object of assignment is the value returned by the operator [].

If the operator [] returns a pointer, the following statement must be written as follows:

* v[5]= 10;

But this will make v look like a vector pointer. So you will choose to let the operator return a reference. There is an interesting exception, see article 30. )

You should not use pointers when you know that you must point to an object and don't want to change its pointing, or when overloading operators to prevent unnecessary semantic misunderstanding. In other cases, you should use pointers to assume that you have

void func(int* p,int & ampr);

int a = 1;

int b = 1;

func(& amp; a,b);

The value of the pointer itself (address value) is realized by passing the value. You can change the address value, but this will not change the value of the variable pointed by the pointer.

P = someotherpointer//a or 1

But the pointer can be used to change the value of the variable pointed by the pointer,

* p = 123 13 1; // a is now 123 13 1

But the reference itself is generated by pass byreference, and changing its value means changing the value of the variable corresponding to the reference.

r = 123 1; // b Now it is 123 1

Use references whenever possible and use pointers if necessary.

When "redirection" is not needed, the reference is usually selected first, and then the pointer is selected. This usually means that the public interface of the reference class is more useful. The typical case of reference is the surface of the object, while the pointer is used inside the object.

The above exception is when the parameter or return value of a function needs a "key" reference. At this time, it is usually best to return/get a pointer and use a null pointer to complete this special task. (References should always be aliases of objects, not null pointers that are dereferenced).

Note: Traditional C programmers sometimes dislike references because they cannot provide clear reference semantics in the caller's code. However, when you have some experience in C++, you will soon realize that this is a form of information hiding, and its advantages outweigh its disadvantages. Just like, programmers should write code for the problem to be solved, not the machine itself.