2

After reading a description about swapping pointer addresses on Stackoverflow, I have a question about C++ syntax for references.

If you have a function with the following signature:

void swap(int*& a, int*& b)

What is the meaning of int*& ? Is that the address of a pointer to an integer? And furthermore being that it is a pointer reference, why is it not required for them to be initialized as follows?

void swap(int*& a, int*& b) : a(a), b(b) {}

Here's the reference question/answer posting (the answer is the point of interest): Swapping addresses of pointers in c

Community
  • 1
  • 1
CJJ
  • 358
  • 1
  • 4
  • 12

4 Answers4

3

A reference to an int pointer. This function would be called as follows:

int* a=...; //points to address FOO
int* b=...; //points to address BAR
swap(a,b);
//a now points to address BAR
//b now points to address FOO
Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
1

It's a reference to an int pointer.

You might find this helpful: Difference between pointer variable and reference variable in c++

Community
  • 1
  • 1
Plynx
  • 11,341
  • 3
  • 32
  • 33
1

Example that demonstrates how pointer references are used:

int items[] = {42, 43};
int* a = &items[0];
int* b = &items[1];
swap(a, b);
// a == &items[1], b == &items[0]
// items in the array stay unchanged
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
1

Because swap here is a function, not a class. Your second code snippet is not valid C++ syntax (you are trying to mix function declaration with a class constructor.)

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171