简体   繁体   中英

What is the behaviour of int &a = *b?

For example, I have the following codes:

int a = 1;
int b = 2;
int *c = &a;
int &d = *c;
c = &b;
d++;

What is behaviour of line 4? If i want a reference to a pointer,is it correct to use

int *&e = c;

Is there any reason why to choose a reference to a pointer?

This declaration

int &d = *c;

declares a reference that refers the object pointed to by pointer c .

When this declaration was executed pointer c pointed to object a

int *c = &a;

So the referecne d refers object a . References may not be reassigned. They shall be initialized when they are declared.

Thus the expression in statement

d++;

increases object a.

You may declare a reference to a pointer.

This declaration

int *&e = c;

is valid.

Constant references can be bound to a temporary object. You may not take an address of a temporary object. Refrences alow to use more simple expressions.

Consider for example a simplified function swap that swaps two integers.

Using pointers the function would look like

void swap( int *a, int *b )
{
   int tmp = *a;
   *a = *b;
   *b = tmp;
} 

and it could be called like

int a = 5;
int b = 10;

swap( &a, &b );

Using references you could write the function the following way

void swap( int &a, int &b )
{
   int tmp = a;
   a = b;
   b = tmp;
} 

and its call would look simpler than the call of the function with pointers.

int a = 5;
int b = 10;

swap( a, b );
  1. regarding the meaning of line 4

    int a = 1; int*c = &a; // okay: pointer to int, points to a int&d = *c; // okay; reference to int, refers to *c=a;
  2. A reference to a pointer is useful as argument to a function that may alter its value (=address pointed to), for example

    void allocate(int*&p) { p=new int[10]; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM