C + + pointers and references

Source: Internet
Author: User

★ Same point:

1. Is the concept of the address;

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

★ Difference:

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

2. The reference does not need to dereference (*), the pointer needs to be dereferenced;

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

Reference "mindedness" ^_^

4. Reference does not have a const, pointer has const,const pointer is immutable;

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

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

typeID (t) = = typeid (t&) constant is true, sizeof (t) = = sizeof (t&) 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 self-increment (+ +) operation has different meanings;

★ Contact

1. References are implemented within the language using pointers (how do I do that?) )。

2. For general applications, the reference is interpreted as a pointer and does not make a serious semantic error. A reference is a pointer to a restricted operation (allow only the content operation).

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 the quoted (referent).

int m;

int &n = m;

N is equivalent to an M alias (nickname), and any action on N is an operation on M. For example, someone named Wang Xiaomao, whose nickname is "Sanmao". Say "Sanmao" how how, in fact is to Wang Xiao judge. 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) The reference is created and must be initialized (the pointer can be initialized at any time).

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

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

In the following sample program, K is initialized as a reference to I. The statement k = J cannot modify k to be a reference to J, just change 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 &k = i;

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

The above program looks like you're playing a word game and doesn't reflect the value of the quote. The primary function of a reference is the parameter and return value of the passed function. In the C + + language, the parameters and return values of a function are passed in three ways: value passing, pointer passing, and reference passing.

The following is a sample program for "Value passing". 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 passing". 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 passing." Since x in the FUNC3 function body is a reference to an 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

In contrast to the above three sample programs, it is found that "reference passing" is of the nature of "pointer passing" and is written like "value passing". In fact, anything that "references" can do "pointers" can also be done, why "reference"

This thing?

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

Pointers can manipulate things in memory without restraint, although pointers are powerful, but very dangerous.

Like a knife, it can be used to cut trees, cut paper, manicure, barber, etc., who dares to use it?

If you really only need to borrow an "alias" for an object, use "reference" instead of "pointer" to avoid an unexpected occurrence. For example, someone needs a proof that the seal on the document would have been stamped on it, and if the key to the official seal is given to him, then he has acquired the right not to.

——————————

Excerpt from "High quality C + + programming"

Pointers and references, in the moreeffective C + + clause I'll give you the details.

Article one: The difference between a pointer and a reference

Pointers and references look completely different (pointers are using the operator ' * ' and '-a ', referencing the operator '). '), but they seem to have the same function. Pointers and references let you refer to other objects indirectly. How do you decide when to use a pointer and when to use a 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 point it to an object, but that 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 is definitely pointing to an object, such as 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 would this code have?" ”

Char *pc = 0;//Sets the pointer to a null value

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

This is very harmful, no doubt about it. The result will be indeterminate (the compiler can produce some output, causing anything to happen) and should avoid the person who writes the code unless they agree to correct the error. If you are concerned that such code will appear in your software, then you'd better avoid using references altogether, or let better programmers 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 pointing s

Pointers do not have such a limitation.

String *ps;//uninitialized pointer

Legal, but dangerous.

The fact that there are no references to null values means that using the referenced code is more efficient than using pointers. Because you do not need to test its legitimacy before using a reference.

void printdouble (const double& RD)
{
cout << Rd; You do not need to test Rd, it
}//must 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 if NULL
cout << *PD;
}
}

Another important difference between pointers and references is that pointers can be re-assigned to point to another different object. But the reference always points to the object that was specified at initialization and cannot be changed later.

String S1 ("Nancy");
String S2 ("Clancy");
string& rs = s1; RS reference S1
String *ps = &s1; PS Pointing S1
rs = s2; Rs still references S1, modified RS is modified 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 when you consider the possibility of not pointing to any object (in which case you can set the pointer to null), and you need to be able to point to different objects at different times (in which case you can change the pointer's direction). If you always point to an object and do not change the point once it points to an object, then you should use a reference.

Another case is that when you reload 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 (vector), the size of 10;
A vector is a template in the standard C library (see clause 35)
V[5] = 10; The target object that is assigned is the value returned by the operator []
If the operator [] returns a pointer, then the latter statement has to be written like this:
*V[5] = 10;

But that would make v look like a vector pointer. So you would choose to have the operator return a reference. (There is an interesting exception to this, see clause 30)

You should not use pointers when you know that you must point to an object and do not want to change its point, or if you overload the operator and are misunderstood to prevent unnecessary semantics. 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 (address value) is Passby 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

But you can use the pointer to change the value of the variable pointed to by the pointer,

*p = 123131;//A now is 123131

But the reference itself is carried out by pass byreference, changing its value to change the value of the variable that the reference corresponds to.

r = 1231;//B now is 1231

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

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

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

Note: Traditional C programmers sometimes do not like references because they do not provide clear citation semantics at the caller's code. However, when you have some C + + experience, you will soon realize that this is a form of information hiding, which is beneficial rather than harmful. As is the case, the programmer should write code for the problem to be solved, not the machine itself.

2. The difference between a pointer and a reference when passed as a function parameter.

(1) The pointer is passed as a parameter:

#include <iostream>using namespace std;void swap (int *a,int *b) {int temp=*a;  *a=*b; *b=temp;}  int main (void) {int a=1,b=2;  Swap (&A,&B);  cout<<a<< "" <<b<<endl;  System ("pause"); return 0;}

The result was 2 1;

By passing parameters with pointers, you can achieve the purpose of changing the arguments, because the address of the actual argument is passed, so the use of *a is actually the data in the memory unit that takes the stored arguments, that is, the actual parameters are changed, so you can achieve the purpose.

Look at a program again;

#include <iostream>using namespace std;void test (int *p) {int a=1;  p=&a; cout<<p<< "" <<*p<<endl;} int main (void) {    int *p=null;    Test (p);    if (p==null)    cout<< "Pointer p is NULL" <<endl;    System ("pause");    return 0;}

The result of the operation is:

0X22FF44 1

Pointer P is null

People may feel strange, what is the matter, is not to pass the address, how p back to null? In fact, a pointer p is declared in the main function, and the value is null, when the test function is called, the address is actually passed, but the address is passed. That is, when the pointer is passed as a parameter, the value is actually passed, but the address is passed. When the pointer is passed as a parameter, it is also a copy of the argument is passed to the formal parameter, that is, the above program main function in the P-test function of the p is not the same variable, storing 2 variable p cell is not the same (just 2 p points to the same storage unit), The change to p in the test function does not affect the value of p in the main function.

If you want to achieve and simultaneously modify the purpose, you have to use the reference.

2. Pass the reference as a parameter to the function.

When a reference is passed as a function parameter, it is essentially passing the argument itself, that is, not a copy of the argument passed in, so the modification of the formal parameter is actually a modification of the actual parameter, so when the parameter is passed by reference, it not only saves time, but also saves space.

Look at the following procedure:

#include <iostream>using namespace std;void test (int &a) {cout<<&a<< "" <<a<< Endl;} int main (void) {    int a=1;    cout<<&a<< "" <<a<<endl;    Test (a);    System ("pause");    return 0;}

The output is: 0x22ff44 1

0X22FF44 1

Look at this program again:

This is enough to show that arguments are passed by reference, actually passing the argument itself, not the copy.

So in order to achieve the purpose of modifying pointers at the same time, we have to use references.

#include <iostream>using namespace std;void test (int *&p) {int a=1;  p=&a; cout<<p<< "" <<*p<<endl;} int main (void) {    int *p=null;    Test (p);    if (p!=null)    cout<< "Pointer p is not NULL" <<endl;    System ("pause");    return 0;}

The output is: 0x22ff44 1

Pointer p is not NULL

The pointer is the address, the reference is the original object itself, and the action reference is the operation source object.

C + + pointers and references

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.