Links to C ++ and C Pointers

Possible duplicate:
What are the differences between a pointer variable and a reference variable in C ++?

I hugged pointers to C (basics anyway) and started reading in C ++. The book that I am reading jumps right into the links, and the search in the index does not go to the pointers until later.

In C, I thought that if I wanted to skip the reference function, I would have to use pointers as arguments, for example.

void swapAandB(int *A, int *B){ //do something } 

But the C ++ book decides to put references to the source variable in the function. eg.

 void swapAandB(int& A, int& B){ //do something } 

My book in C ++ did not explain why we do not use pointers, as in C. Therefore, I am a little confused. I think my question is: what's going on here?

+4
source share
4 answers

Links and an additional mechanism that C ++ provides compared to C. Using pointers to C ++ is completely legal, so you can define your first function without changes:

 void swapAandB(int *A, int *B){ //do something } 

The main advantage that pointer references offer is that it is not so easy to have the equivalent of a NULL pointer. But links, both semantically and syntactically, go far beyond this in the formation of C ++ functions as a language. I think it will become clearer when you switch to the language. In any case, you can try reading this article about the difference between pointers and links .

+5
source

You can use pointers, as in C, but links are aliases of objects, so the object exists, you do not need to check if they are valid. There are differences with pointers in their use:

 void foo(Type * pointer) { if (pointer) pointer->data_ = ....; } void foo(Type & reference) { reference.data_ = ....; } Type obj; foo(&obj); // pointer syntax foo(obj); // reference syntax 

In addition, the link always "points" to the same object, so you will always use it correctly.

+2
source

In this case, pointers and links will behave the same.
The only difference is how you call them:

 int x, y; swapAandB( &x, &y ); // here you pass the variables' addresses to the pointer function swapAandB( x, y ); // here you pass the variables' reference to the reference function 

The result is the same, the variables are not copied, but rather are referenced from within the functions, and any changes that you apply to them inside the function will affect the variables in the call area.

0
source

Typically: Try using links instead of pointers.

In some cases, you need to use pointers:

  • polymorphism
  • you need something like a null pointer
  • you need to delete the variable later
-1
source

Source: https://habr.com/ru/post/1381135/


All Articles