E
Eric Lilja
...during the call to swap_arrays the name of the array decays to a
pointer to its first element and that pointer is a temporary variable
and you cant bind a non-const reference to a temporary. Correct
analysis?
The code (that only compiles if you comment out the call to
swap_arrays()):
#include <iostream>
#include <iterator>
using namespace std;
void swap_arrays(int *&a1, int *&a2)
{
int *ptr = a1;
a1 = a2;
a2 = ptr;
}
int main()
{
int array1[] = {1, 2, 3};
int array2[] = {4, 5, 6};
swap_arrays(array1[0], array2[0]);
cout << "array1 after swap:" << endl;
copy(array1, array1 + sizeof(array1) / sizeof(array1[0]),
ostream_iterator<int>(cout, " "));
cout << endl << "array2 after swap:" << endl;
copy(array2, array2 + sizeof(array2) / sizeof(array2[0]),
ostream_iterator<int>(cout, " "));
cout << endl;
}
pointer to its first element and that pointer is a temporary variable
and you cant bind a non-const reference to a temporary. Correct
analysis?
The code (that only compiles if you comment out the call to
swap_arrays()):
#include <iostream>
#include <iterator>
using namespace std;
void swap_arrays(int *&a1, int *&a2)
{
int *ptr = a1;
a1 = a2;
a2 = ptr;
}
int main()
{
int array1[] = {1, 2, 3};
int array2[] = {4, 5, 6};
swap_arrays(array1[0], array2[0]);
cout << "array1 after swap:" << endl;
copy(array1, array1 + sizeof(array1) / sizeof(array1[0]),
ostream_iterator<int>(cout, " "));
cout << endl << "array2 after swap:" << endl;
copy(array2, array2 + sizeof(array2) / sizeof(array2[0]),
ostream_iterator<int>(cout, " "));
cout << endl;
}