Differences between references and pointers in C ++

Source: Internet
Author: User

There are three major differences between reference and pointer:
1. The reference must be initialized and the pointer is not required.
2. The reference cannot be changed after initialization. the pointer can change the variable.
3. There is no reference pointing to a null value, but there is a pointer pointing to a null value.

 

 

 

Differences between references and pointers in C ++

★Similarities:

1. All are addresses;

The Pointer Points to a piece of memory, and its content refers to the memory address;A reference is the alias of a block of memory.

★Differences:

1. the pointer is an entity, and the reference is only an alias;

2. You do not need to unreference (*) when using a reference. The pointer must be unreferenced;

3. The reference can only be initialized once during definition, and will not be changed afterwards; the pointer will be variable;

Reference "from one end" ^_^

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

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

6. "sizeof reference" gets the size of the variable (object) to which it points, while "sizeof Pointer" gets the size of the pointer itself (the address of the variable or object to which it points;

Typeid (t) = typeid (T &) always true, sizeof (t) = sizeof (T &) always true, but when referencing as a member, the occupied space is the same as the pointer (no standard rule is found ).

7. the pointer and reference auto-increment (++) operations have different meanings;

★Contact

1. Reference is implemented using pointers inside the language (how to implement it ?).

2. For general applications, the reference is understood as a pointer and no serious semantic error is made. A reference is a pointer with limited operations (only content operations are allowed ).

References are a concept in C ++. Beginners can easily confuse references with pointers. In the following program, n is a reference of M, and M is a referent ).

Int m;

Int & n = m;

N is equivalent to M alias (nickname). Any operation on N is an operation on M. For example, someone named Wang xiaomao, whose nickname is "San Mao ". The reason for saying "three hairs" is actually to say three things to Wang xiaomao. Therefore, n is neither a copy of M nor a pointer to M. In fact, n is m itself.

Some referenced rules are as follows:

(1) The reference must be initialized at the same time (the pointer can be initialized at any time ).

(2) there cannot be a null reference, and the reference must be associated with a valid storage unit (the pointer can be null ).

(3) once the reference is initialized, the reference relationship cannot be changed (the pointer can change the object at any time ).

In the following example, K is initialized as a reference of I. Statement K = J cannot be changed to j Reference, but the value of K is changed to 6. Because K is an I reference, the value of I is also changed to 6.

Int I = 5;

Int J = 6;

Int & K = I;

K = J; // The values of K and I are changed to 6;

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

The following is a sample program for "value transfer. Since X in the func1 function is a copy of the external variable N, changing the value of X does not affect N, so the value of N is still 0.

Void func1 (int x)
{
X = x + 10;
}
Int n = 0;
Func1 (N );
Cout <"n =" <n <Endl; // n = 0

 
The following is an example program for "pointer passing. Since X in the func2 function 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 is 10.

Void func2 (int * X)
{
(* X) = (* x) + 10;
}
& #8943;
Int n = 0;
Func2 (& N );
Cout <"n =" <n <Endl; // n = 10

 
The following is a sample program for "reference transfer. Since X in the func3 function is referenced by the external variable n, x and n are the same thing, changing X equals to changing N, so the value of N becomes 10.

Void func3 (Int & X)
{
X = x + 10;
}
& #8943;
Int n = 0;
Func3 (N );
Cout <"n =" <n <Endl; // n = 10

 
Comparing the above three examples, we will find that the nature of "Reference transfer" is like "pointer transfer", and the writing method is like "value transfer ". In fact, "reference" can be used to do anything "pointer". Why do we need to "reference"

This thing?

The answer is "Use appropriate tools for proper work ".

Pointers can operate on the memory without any constraints. Although pointers are powerful, they are very dangerous.

Like a knife, which can be used to cut trees, cut paper, manicure, and cut hair. Who dares to use it like this?

If you only need to borrow the "alias" of an object, use "Reference" instead of "Pointer" to avoid exceptions. For example, a person needs a proof that the seal was originally printed on the document. If he handed over the key to the seal, he would have obtained the right he did not have.

----------

From "high quality c ++ programming 」

Pointers and references are described in detail in terms of more than tive C ++. I will forward them to you.

Clause 1: differences between pointers and references

The pointer and reference seem completely different (the pointer uses the operators '*' and '->' and references the operator '. '), But they seem to have the same functionality. Both pointer and Reference allow you to indirectly reference other objects. How do you decide when to use pointers and when to use references?

First, you must realize that the reference pointing to a null value cannot be used under any circumstances. A reference must always point to some objects. Therefore, if you use a variable and direct it to an object, but the variable may not point to any object at some time, you should declare the variable as a pointer, in this way, you can assign a null value to the variable. On the contrary, if the variable must point 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." You asked with suspicion, "What are the consequences of such code ?"

Char * Pc = 0; // set the pointer to a null value

Char & rc = * PC; // point the reference to a null value

This is very harmful and there is no doubt. The results will be uncertain (the compiler can generate some output, causing everything to happen) and should avoid the people who write such code unless they agree to correct the error. If you are worried that such code will appear in your software, you 'd better avoid using references completely, or else let better programmers do it. In the future, we will ignore the possibility that a reference points to a null value.

Because the reference will certainly point to an object, in C, the reference should be initialized.

String & RS; // error. The reference must be initialized.

String S ("Xyzzy ");

String & rs = s; // correct. RS points to S.

Pointers do not have such restrictions.

String * pS; // uninitialized pointer

// Valid but dangerous

The fact that there is no reference pointing to a null value means that the code to be referenced is more efficient than the pointer. Because you do not need to test its validity before using the reference.

Void printdouble (const double & rd)
{
Cout <RD; // No need to test Rd, it
} // Definitely points to a double value
Instead, pointers should always be tested to prevent being empty:
Void printdouble (const double * PD)
{
If (PD)

{// Check whether it is null
Cout <* PD;
}
}

 
Another important difference between a pointer and a reference is that a pointer can be re-assigned to point to another object. However, the reference always points to the specified object during initialization and cannot be changed later.

String S1 ("Nancy ");
String S2 ("Clancy ");
String & rs = S1; // Rs references S1
String * PS = & S1; // PS points to S1
Rs = S2; // Rs still references S1,
// But the value of S1 is
// "Clancy"
PS = & S2; // PS is now directed to S2;
// S1 has not changed

 
In general, you should use pointers 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 null ), second, you need to be able to point to different objects at different times (in this case, you can change the pointer ). If you always point to an object and it does not change its direction once it points to an object, you should use references.

Another case is that when you reload an operator, you should use references. The most common example is the operator []. A typical usage of this operator is to return a target object, which can be assigned a value.

Vector <int> V (10); // create an integer vector (vector) with a size of 10;
// Vector is a template in the Standard C library (see article 35)
V [5] = 10; // the target object to be assigned is the value returned by the operator [].
If the operator [] returns a pointer, the next statement must be written as follows:
* V [5] = 10;

 
However, this will make V look like a vector pointer. Therefore, you will choose to let the operator return a reference. (This is an interesting exception. Refer to Clause 30)

When you know that you must point to an object and do not want to change its direction, or when you overload operators and prevent unnecessary semantic misunderstanding, you should not use pointers. In other cases, the pointer should be used to assume that you have

Void func (int * P, Int & R );
Int A = 1;
Int B = 1;
Func (& A, B );

 
The value (address value) of the pointer is carried out by pass by value. You can change the address value, but this does not change the value of the variable pointed to by the pointer,

P = someotherpointer; // A is still 1

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

* P = 123131; // a now is 123131

However, the reference itself is carried out by pass by reference. changing its value changes the value of the variable corresponding to the reference.

R = 1231; // B now is 1231

Use references whenever possible, and use pointers whenever necessary.

When you do not need to "Redirect", the reference is generally preferred over the pointer. This usually means that it is more useful to reference public interfaces for classes. A reference typically appears on the surface of an object, and a pointer is used inside the object.

The exception is that the parameter or return value of a function requires a "critical" reference. In this case, it is usually better to return/obtain a pointer and use a null pointer to accomplish this Special Mission. (The reference should always be the alias of the object, rather than the NULL pointer that is removed from the reference ).

Note: Since clear reference semantics cannot be provided in the caller's code, traditional C Programmers sometimes do not like to reference it. However, with some C ++ experience, you will soon realize that this is a form of information hiding, which is beneficial rather than harmful. Just as, programmers should write code for the problem to be solved, rather than the machine itself.

There are three major differences between reference and pointer:
1. The reference must be initialized and the pointer is not required.
2. The reference cannot be changed after initialization. the pointer can change the variable.
3. There is no reference pointing to a null value, but there is a pointer pointing to a null value.

 

 

 

Differences between references and pointers in C ++

★Similarities:

1. All are addresses;

The Pointer Points to a piece of memory, and its content refers to the memory address;A reference is the alias of a block of memory.

★Differences:

1. the pointer is an entity, and the reference is only an alias;

2. You do not need to unreference (*) when using a reference. The pointer must be unreferenced;

3. The reference can only be initialized once during definition, and will not be changed afterwards; the pointer will be variable;

Reference "from one end" ^_^

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

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

6. "sizeof reference" gets the size of the variable (object) to which it points, while "sizeof Pointer" gets the size of the pointer itself (the address of the variable or object to which it points;

Typeid (t) = typeid (T &) always true, sizeof (t) = sizeof (T &) always true, but when referencing as a member, the occupied space is the same as the pointer (no standard rule is found ).

7. the pointer and reference auto-increment (++) operations have different meanings;

★Contact

1. Reference is implemented using pointers inside the language (how to implement it ?).

2. For general applications, the reference is understood as a pointer and no serious semantic error is made. A reference is a pointer with limited operations (only content operations are allowed ).

References are a concept in C ++. Beginners can easily confuse references with pointers. In the following program, n is a reference of M, and M is a referent ).

Int m;

Int & n = m;

N is equivalent to M alias (nickname). Any operation on N is an operation on M. For example, someone named Wang xiaomao, whose nickname is "San Mao ". The reason for saying "three hairs" is actually to say three things to Wang xiaomao. Therefore, n is neither a copy of M nor a pointer to M. In fact, n is m itself.

Some referenced rules are as follows:

(1) The reference must be initialized at the same time (the pointer can be initialized at any time ).

(2) there cannot be a null reference, and the reference must be associated with a valid storage unit (the pointer can be null ).

(3) once the reference is initialized, the reference relationship cannot be changed (the pointer can change the object at any time ).

In the following example, K is initialized as a reference of I. Statement K = J cannot be changed to j Reference, but the value of K is changed to 6. Because K is an I reference, the value of I is also changed to 6.

Int I = 5;

Int J = 6;

Int & K = I;

K = J; // The values of K and I are changed to 6;

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

The following is a sample program for "value transfer. Since X in the func1 function is a copy of the external variable N, changing the value of X does not affect N, so the value of N is still 0.

Void func1 (int x)
{
X = x + 10;
}
Int n = 0;
Func1 (N );
Cout <"n =" <n <Endl; // n = 0

 
The following is an example program for "pointer passing. Since X in the func2 function 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 is 10.

Void func2 (int * X)
{
(* X) = (* x) + 10;
}
& #8943;
Int n = 0;
Func2 (& N );
Cout <"n =" <n <Endl; // n = 10

 
The following is a sample program for "reference transfer. Since X in the func3 function is referenced by the external variable n, x and n are the same thing, changing X equals to changing N, so the value of N becomes 10.

Void func3 (Int & X)
{
X = x + 10;
}
& #8943;
Int n = 0;
Func3 (N );
Cout <"n =" <n <Endl; // n = 10

 
Comparing the above three examples, we will find that the nature of "Reference transfer" is like "pointer transfer", and the writing method is like "value transfer ". In fact, "reference" can be used to do anything "pointer". Why do we need to "reference"

This thing?

The answer is "Use appropriate tools for proper work ".

Pointers can operate on the memory without any constraints. Although pointers are powerful, they are very dangerous.

Like a knife, which can be used to cut trees, cut paper, manicure, and cut hair. Who dares to use it like this?

If you only need to borrow the "alias" of an object, use "Reference" instead of "Pointer" to avoid exceptions. For example, a person needs a proof that the seal was originally printed on the document. If he handed over the key to the seal, he would have obtained the right he did not have.

----------

From "high quality c ++ programming 」

Pointers and references are described in detail in terms of more than tive C ++. I will forward them to you.

Clause 1: differences between pointers and references

The pointer and reference seem completely different (the pointer uses the operators '*' and '->' and references the operator '. '), But they seem to have the same functionality. Both pointer and Reference allow you to indirectly reference other objects. How do you decide when to use pointers and when to use references?

First, you must realize that the reference pointing to a null value cannot be used under any circumstances. A reference must always point to some objects. Therefore, if you use a variable and direct it to an object, but the variable may not point to any object at some time, you should declare the variable as a pointer, in this way, you can assign a null value to the variable. On the contrary, if the variable must point 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." You asked with suspicion, "What are the consequences of such code ?"

Char * Pc = 0; // set the pointer to a null value

Char & rc = * PC; // point the reference to a null value

This is very harmful and there is no doubt. The results will be uncertain (the compiler can generate some output, causing everything to happen) and should avoid the people who write such code unless they agree to correct the error. If you are worried that such code will appear in your software, you 'd better avoid using references completely, or else let better programmers do it. In the future, we will ignore the possibility that a reference points to a null value.

Because the reference will certainly point to an object, in C, the reference should be initialized.

String & RS; // error. The reference must be initialized.

String S ("Xyzzy ");

String & rs = s; // correct. RS points to S.

Pointers do not have such restrictions.

String * pS; // uninitialized pointer

// Valid but dangerous

The fact that there is no reference pointing to a null value means that the code to be referenced is more efficient than the pointer. Because you do not need to test its validity before using the reference.

Void printdouble (const double & rd)
{
Cout <RD; // No need to test Rd, it
} // Definitely points to a double value
Instead, pointers should always be tested to prevent being empty:
Void printdouble (const double * PD)
{
If (PD)

{// Check whether it is null
Cout <* PD;
}
}

 
Another important difference between a pointer and a reference is that a pointer can be re-assigned to point to another object. However, the reference always points to the specified object during initialization and cannot be changed later.

String S1 ("Nancy ");
String S2 ("Clancy ");
String & rs = S1; // Rs references S1
String * PS = & S1; // PS points to S1
Rs = S2; // Rs still references S1,
// But the value of S1 is
// "Clancy"
PS = & S2; // PS is now directed to S2;
// S1 has not changed

 
In general, you should use pointers 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 null ), second, you need to be able to point to different objects at different times (in this case, you can change the pointer ). If you always point to an object and it does not change its direction once it points to an object, you should use references.

Another case is that when you reload an operator, you should use references. The most common example is the operator []. A typical usage of this operator is to return a target object, which can be assigned a value.

Vector <int> V (10); // create an integer vector (vector) with a size of 10;
// Vector is a template in the Standard C library (see article 35)
V [5] = 10; // the target object to be assigned is the value returned by the operator [].
If the operator [] returns a pointer, the next statement must be written as follows:
* V [5] = 10;

 
However, this will make V look like a vector pointer. Therefore, you will choose to let the operator return a reference. (This is an interesting exception. Refer to Clause 30)

When you know that you must point to an object and do not want to change its direction, or when you overload operators and prevent unnecessary semantic misunderstanding, you should not use pointers. In other cases, the pointer should be used to assume that you have

Void func (int * P, Int & R );
Int A = 1;
Int B = 1;
Func (& A, B );

 
The value (address value) of the pointer is carried out by pass by value. You can change the address value, but this does not change the value of the variable pointed to by the pointer,

P = someotherpointer; // A is still 1

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

* P = 123131; // a now is 123131

However, the reference itself is carried out by pass by reference. changing its value changes the value of the variable corresponding to the reference.

R = 1231; // B now is 1231

Use references whenever possible, and use pointers whenever necessary.

When you do not need to "Redirect", the reference is generally preferred over the pointer. This usually means that it is more useful to reference public interfaces for classes. A reference typically appears on the surface of an object, and a pointer is used inside the object.

The exception is that the parameter or return value of a function requires a "critical" reference. In this case, it is usually better to return/obtain a pointer and use a null pointer to accomplish this Special Mission. (The reference should always be the alias of the object, rather than the NULL pointer that is removed from the reference ).

Note: Since clear reference semantics cannot be provided in the caller's code, traditional C Programmers sometimes do not like to reference it. However, with some C ++ experience, you will soon realize that this is a form of information hiding, which is beneficial rather than harmful. Just as, programmers should write code for the problem to be solved, rather than the machine itself.

There are three major differences between reference and pointer:
1. The reference must be initialized and the pointer is not required.
2. The reference cannot be changed after initialization. the pointer can change the variable.
3. There is no reference pointing to a null value, but there is a pointer pointing to a null value.

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.