C + + reference vs. pointers (emphasis on understanding)

Source: Internet
Author: User

★ The same point:

1. The concept of address;

The pointer points to a piece of memory whose contents are the address of the memory, and the reference is an alias to a block of memory.

★ Difference:

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

2. References need not be referenced (*), the pointer needs to dereference;

3. References can only be initialized once at the time of definition, and then immutable, and the pointer is variable;

Refer to the "one-woman" ^_^

4. The reference does not have a const, the pointer has a const,const pointer immutable;

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

6. The "sizeof reference" obtains the size of the variable (object) to which it is pointed, and the "sizeof pointer" gets the size of the pointer itself (the address of the variable or object to which it is directed);

typeID (t) = = typeid (t&) constant is true, sizeof (t) = = sizeof (t&) constant is true, but when referenced as a member, it occupies the same space as the pointer (no Standard rules found).

7. The pointer and the reference of the self-increase (+ +) operation is not the same meaning;

★ Contact

1. References are implemented within the language using pointers (how to implement them). )。

2. For general applications, a reference to a pointer does not make a serious semantic error. A reference is a pointer to an operation that is restricted (only the fetch operation is allowed).

References are concepts in C + +, and beginners tend to confuse references with pointers. In the program, N is a reference to M (reference), and M is a referenced object (referent).

int m;

int &n = m;

N is equivalent to M's alias (nickname), and any action on N is an operation on M. For example, someone named Wang Xiaomao, his nickname is "Sanmao". Say "Sanmao" how how, in fact, is to Wang Mao. So n is neither a copy of M nor a pointer to M, in fact N is the M itself.

Some of the rules cited are as follows:

(1) When a reference is created, it must be initialized (the pointer can be initialized at any time).

(2) cannot have a null reference, the reference must be associated with a legitimate storage unit (the pointer can be null).

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

In the following example program, K is initialized to a reference to I. The statement k = J does not change K to be a reference to J, but changes the value of K to 6. Since k is a reference to I, the value of I has also become 6.

int i = 5;

int j = 6;

int &k = i;

The values of k = j;/k and I are all changed to 6;

The above program looks like it's playing word games and doesn't reflect the value of references. The primary function of a reference is to pass the function's arguments and return values. In the C + + language, the parameters and return values of functions are passed in three different ways: value passing, pointer passing, and reference passing.

The following is a sample program for value delivery. Since x in the FUNC1 function body 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 a sample program for "pointer delivery." Since x in the FUNC2 function body is a pointer to an external variable n, changing the contents of the pointer will cause the value of N to change, so the value of n becomes 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 delivery. Since the x in the body of the FUNC3 function 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 Func3 (int &x)
{
x = x + 10;
}
& #8943;
int n = 0;
FUNC3 (n);
cout << "n =" << n << Endl; n = 10

Comparing the three sample programs above, you will find that the nature of the reference pass is like "pointer passing", and the writing is like "value delivery." In fact, anything that "references" can do, "pointers" are also able to do, why "reference"

This thing.

The answer is "to do the right thing with proper tools".

Pointers can manipulate what is in memory without constraint, although the pointer is powerful but dangerous.

Like a knife, it can be used to cut trees, paper, manicure, Barber and so on, who dares to use this.

If you really just need to borrow an object's "alias", use "reference" instead of "pointers" to avoid surprises. For example, a person needs a certificate, originally in the document stamped seal on the line, if the official seal of the key to him, then he won the wrong right.

——————————

Excerpt from "High quality C + + programming"

Pointers and references, in the moreeffective C + + Terms of a detailed story, I'll give you a turn around

Article one: The difference between a pointer and a reference

The pointer looks completely different from the reference (the pointer uses the operator ' * ' and '-> ' to refer to the use operator '.) '), but they seem to have the same functionality. Pointers and references allow you to indirectly refer to other objects. How do you decide when to use the pointer and when to use the reference?

First, realize that you cannot use a reference to a null value under any circumstances. A reference must always point to some object. So if you use a variable and let it point to an object, but the variable may not point to any object at some point, you should declare the variable as a pointer, because you can assign a null value to the variable. Conversely, if the variable definitely 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 wait a minute," you asked suspiciously, "what kind of consequences such a code would have." ”

Char *pc = 0;//set pointer to null value

char& rc = *pc;//Let reference point to null value

This is very harmful, no doubt. The result will be indeterminate (the compiler can produce some output that could cause anything to happen) and should avoid people who write such code unless they agree to correct the error. If you're worried that the code will appear in your software, you'd better avoid using references altogether, or you can get better programmers to do it. We will later ignore the possibility of a reference pointing to a null value.

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

string& rs;//Error, reference must be initialized

String S ("Xyzzy");

string& rs = s;//correct, RS points to S

The pointer has no such restriction.

String *ps;//uninitialized pointer

Legal but dangerous

The fact that there is no reference to a null value means that the code that uses the reference is more efficient than using the pointer. Because you do not need to test the legality of a reference before using it.

void printdouble (const double& RD)
{
cout << Rd; You don't need to test Rd, it
//Definitely point to a double value
Instead, the pointer should always be tested to prevent it from being empty:
void printdouble (const double *PD)
{
if (PD)

{//Check for NULL
cout << *PD;
}
}

Another important difference between pointers and references is that pointers can be assignable to point to another different object. However, references always point to objects that are specified at initialization time and cannot be changed later.

String S1 ("Nancy");
String S2 ("Clancy");
string& rs = s1; RS reference S1
String *ps = &s1; PS Point to S1
rs = s2; RS still quotes S1,
But the value of S1 is now
"Clancy"
PS = &s2; PS now points to S2;
S1 hasn't changed.

In general, you should use pointers in the following situations, one is that you take into account the possibility of not pointing to any object (in this case, you can set the pointer empty), and the second is that you need to be able to point to different objects at different times (in which case you can change the direction of the pointer). If you always point to an object and do not change direction once you point to an object, you should use a reference.

In another case, when you overload an operator, you should use a reference. 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<int> V (10); Set up the shaping vector (vectors) with a size of 10;
A vector is a template in the standard C library (see clause 35)
V[5] = 10; This assigned target object is the value returned by the operator []
If the operator [] Returns a pointer, the latter statement has to be written like this:
*V[5] = 10;

But this makes v look like a vector pointer. So you will choose to have the operator return a reference. (This has an interesting exception, see clause 30)

You should not use pointers when you know that you have to point to an object and you do not want to change its direction, or when overloading the operator and preventing unnecessary semantic misunderstanding. And in other cases, you should use pointers to assume that you have

void func (int* p, int&r);
int a = 1;
int b = 1;
Func (&A,B);

The value of the pointer itself (the address value) is Passby value, you can change the address value, but that does not change the value of the variable that the pointer points to.

p = someotherpointer;//a is still 1

But you can use a pointer to change the value of the variable that the pointer points to.

*p = 123131;/A now is 123131

However, the reference itself is carried out in pass byreference, changing its value to change the value of the variable that the reference corresponds to

R = 1231;//B is 1231

Use references whenever possible and use pointers when you have to.

When you do not need to "point back", the reference generally takes precedence over the pointer being selected. This usually means that referencing a public interface for a class is more useful. A typical situation where a reference occurs is the object's surface, and the pointer is used inside the object.

The above exception is when a function's argument or return value requires a "critical" reference. It is usually best to return/get a pointer and use a NULL pointer to accomplish this particular mission. (The reference should always be an alias for the object, not a null pointer to be dereference).

Note: Because it is not possible to provide a clear citation semantics at the caller's code, traditional C programmers sometimes do not like to refer to them. However, when you have some C + + experience, you will soon realize that this is a form of information hiding, which is useful rather than harmful. As if the programmer should write code for the problem to be solved, not the machine itself.


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.