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
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
It's a reference to an int pointer.
You might find this helpful: Difference between pointer variable and reference variable in c++
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
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.)
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.