问题
template <class T>
void swap(T& a, T& b){
T tmp = a; a = b; b = tmp;
}
I am reading a book and it tells me that the code above will not work for arrays unless we overload the '=' operator. I don't understand why it shouldn't work though. Are we not switching around the pointers to the first index of the arrays?
回答1:
First of all, if you pass arrays as arguments the type T
will be deduced to be an array type, and that leads to problem as you can not assign an array only copy them.
Then your misconception that you can just switch pointers around, that can't be done. If you have two pointers, swapping them will work fine but you can't just switch around arrays like that. And it won't be possible to use pointers to the arrays using the address-of operator directly in the call either, as that will attempt to bind references to temporary values which are not possible.
The only solution to "swap arrays" using your function is something like
char array1[...] = { ... };
char array2[...] = { ... };
char* pointer_to_array1 = array1;
char* pointer_to_array2 = array2;
swap(pointer_to_array1, pointer_to_array2);
// After call, pointer_to_array1 will point to the first element of array2
// and pointer_to_array2 will point to the first element of array1
回答2:
Are we not switching around the pointers to the first index of the arrays?
There is no such thing. It sounds like your mental model of a C-style array is a pointer that points to some elements. However this is wrong. In fact the C-style array is just the elements, there is no pointer.
We can form a temporary pointer to the first element when we need one but there is not such a pointer stored along with the array storage.
Like any other object, an array lives at the same address for its entire lifetime. Swapping two arrays can only be done by swapping the contents of every element.
来源:https://stackoverflow.com/questions/34477753/generic-swap-function-in-c-and-arrays