Comparison of the use of reference and pointers (Pointer) in C + +

Source: Internet
Author: User

Knowing what the difference between reference reference and pointer pointer can help you decide when to use reference and when to use pointer.

In C + +, reference has the same capabilities as pointers (pointer) in many ways. While most C + + programmers have some intuition about when to use reference when using pointer, there are always times when it's unclear. If you want to create a clear and rational concept for using reference, it is important to understand exactly what reference and pointer are different.
Deep meaning

Like pointer, a reference is an object that can be used to point indirectly to another object. A reference declaration is identical to the actual grammatical structure of the pointer declaration. The difference is that when declaring pointer, use the asterisk operator * While declaring reference using the address operator &. For example, we have:
int i = 3;
Then there are:
int *PI = &i;
Declares that pi is a pointer-type object and is a "pointer to int integer" whose initial value is the address of object I. And on the other hand:
int &ri = i;
Declares that RI is an object of type reference and is also a reference to an integral type, which points to I. We can see that the declarations of pointer and reference are significantly different, but this is not the basis for deciding when to use them. The real basis of the decision is that when they are used in an expression, the difference in their display determines which of the appropriate

The biggest difference between Pointer and reference is that Pointer must use an asterisk operator * to get rid of reference (called dereference, I don't know how to translate the word right here, let's call it "reference.") ) and reference does not need any operator to refer to. For example, with the definition in the example above, the indirect expression *pi the Pi to refer to the I. Instead, the expression ri-does not require any operators-automatically refer to the RI to point to I. Therefore, using the pointer p, we need to use an assignment statement:
*p = 4;
To change the value of I to 4, and using reference RIS, we only need to write directly:
RI = 4;
You can also change the value of I to 4.

The difference in this display is significant when you choose whether to use pointer or reference for the function's parameter type and return value type, especially for overloaded operator functions.

This is illustrated by using an example of the + + operator for enumeration types (enumeration). In C + +, the built-in + + operator is not valid for an enumeration type, for example, the following definition:

enum day{    Sunday, Monday, ...    };    Day x;


Expression ++x cannot be compiled. If you want to make it compile, you must define a function named operator++, accept Day as the argument, and call ++x must change the value of X. Therefore, only one function operator++ is declared, with the type day as the parameter, as follows:
Day operator++ (day D);
Not be able to get the desired effect. This function passes the parameter by value (pass by value), which means that a copy of the parameter is seen inside the function, not the parameter itself. In order for the function to change the value of its operand (operand), it must pass its operand through a pointer or reference.

Passing parameters by pointer (passing by pointer), the function is defined as follows:
Day *operator++ (day *d);
It changes the value of the date (day) of the function by storing the added value in the *d. However, you will have to use the expression ++&x to invoke this operator, which does not look very good.

The correct approach is to define operator++ with reference as the parameter type, as follows:

Day &operator+ + (day &D    )    {1)    ; return D;    }


With this function, the expression ++x has the correct display and the correct operation.

Passing by reference is not just a good way to write operator++, but the only way. C + + doesn't give us a choice here. Like the following statement:
Day *operator++ (day *d);
is not compiled. Each overloaded operator function must either be a member of a class, or use the type T, T & or T const & as the parameter type, where T is a class (class) or enumeration (enumeration) type. That is, each overloaded operator must have a class or enumeration type as the parameter type. pointers, even pointers to a class or enumeration type object, are not available. C + + does not allow the meaning of built-in operators to be redefined during overloaded operations, including pointer types. Therefore, we can not define:
int operator++ (int i); Error
Because it attempts to redefine the meaning of the operator + + on int. Nor can we define:
int *operator++ (int *i); Error
Because it attempts to redefine the meaning of the operator + + on int *.
References vs. Const pointers

The definition of "const reference" is not allowed in C + + because a reference is inherently const. That is, once a reference is bound to an object, it is no longer possible to rebind it to another different object. There is no notation after declaring a reference to rebind it to another object. For example:
int &ri = i;
Binds an RI to I. Then the following assignment:
RI = j;
Instead of binding Ri to J, the value in J is assigned to the object that the RI points to, which is the assignment to I.

In short, a pointer can point to many different objects in its lifetime, while a reference can only point to an object. Some people think this is the biggest difference between reference and pointer. I don't approve of it. Perhaps this is a little different from the reference and pointer, but not the difference between reference and const pointer. Once again, once a reference is bound to an object, it cannot be changed to something else. Since it is no longer possible to bind reference and then change, a reference must be bound at birth. Otherwise the reference will never be bound to anything, and it will be useless.

The previous discussion also applies equally to constant pointers (const pointer). (Note that I'm talking about the constant pointer (const pointer) instead of pointing to the constant pointer "pointers to const". For example, a reference declaration must have an initialization assignment, as follows:

void f ()    {    int &r = i;    ...    }


Omitting this initialization assignment will result in a compilation error:

void F ()
{
int &r; Error
...
}

The declaration of a constant pointer must also have an initialization assignment, as follows:

void F ()
{
int *const p = &i;
...
}

Omitting this initialization assignment also makes an error:

void F () {
int *const p; Error
...
}

In my opinion, it is not possible to bind reference two times as reference differs from pointer. is no more significant than the difference between a constant pointer and a very variable pointer.
Null references

In addition to the display, the constant pointer is a little bit different from reference, that is, a valid reference must point to an object, and a pointer does not. A pointer, even if it is a constant pointer, can have a null value. A null pointer does not point to anything.

This difference implies that when you want to be sure that a parameter must point to an object, you should use reference as the parameter type. For example, a swap function, which accepts two int parameters and swaps the values of two parameters, as follows:

int I, J;
Swap (I, j);

Place the value originally in I into J and place the value originally in J in I. We can write this function like this:

void swap (int *v1, int *v2)
{
int temp = *V1;
*V1 = *v2;
*v2 = temp;
}

In this definition, the function is called like this: Swap (&i, &j);

This interface implies that one or two of the parameters may be null (NULL). And this hint is misleading. For example, calling
Swap (&i, NULL);
The consequences are likely to be unpleasant.

and define reference as the parameter as follows:

void swap (int &v1, int &v2)
{
int temp = V1;
V1 = v2;
v2 = temp;
}

It is clear that the call swap should provide two objects whose values will be exchanged. Another benefit of this definition is that when calling this function, you do not need to use those & symbols that look more pleasing to you:
Swap (I, j);
More secure?

Some people think that since reference cannot be empty, it should be more secure than a pointer. I think reference may be a little safer, but not a lot safer. Although a valid reference can not be empty, but invalid. In fact, in many cases it is possible for a program to produce an invalid reference, not just an empty reference. For example, you can define a reference that binds it to an object pointed to by a pointer, as follows:

int *p;
...
int &r = *p;

If the pointer *p is exactly empty when reference is defined, the reference is empty. Technically, the error is not to bind reference to a null value, but to refer to a null pointer. A null pointer to a reference produces an indeterminate operation, which means that a lot of things can happen, and most of them are not good. It is very likely that when the program binds reference R to *p (the object that P points to), p is not actually referenced, even the program simply copies the value of P to the pointer implementing R. And the program will continue to execute until the error is more apparent in the subsequent operation, resulting in unpredictable hazards.

The following function shows another way to produce an invalid reference:

int &f ()
{
int i;
...
return i;
}

This function returns a reference that points to the local variable i. When the function returns, however, the storage space for the local variable I disappears. So this function actually returns a reference that points to the reclaimed space. This operation has the same consequences as returning a pointer to a local variable. Some compilers can find this error at compile time, but there is a good chance that it will not be discovered.

I like reference, and there are good reasons to use them instead of pointer. But if you expect to use reference to make your program more robust, you'll probably be disappointed.

Reprinted from the Programmer's Lab's translation of Dan Saks's article References vs. pointers.

Address: HTTP://WWW.PRGLAB.COM/BLOG/P/28

Original address: http://www.embedded.com/story/OEG20010311S0024

Comparison of the use of reference and pointers (Pointer) in C + +

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.