I do understand that const T*& is a reference of pointer to const type T. The pointer has low-level const so that it won't change the value it points to. However, the following code fails at compile time and gives the following message:
error C2664: 'void pointer_swap(const int *&,const int *&)': cannot convert argument 1 from 'int *' to 'const int *&'.
Is there any way to modify the pointer but prevent the pointed to value from changing in the function?
void pointer_swap(const int *&pi, const int *&pj)
{
const int *ptemp = pi;
pi = pj;
pj = ptemp;
}
int main()
{
int i = 1, j = 2;
int *pi = &i, *pj = &j;
pointer_swap(pi, pj);
return 0;
}
You can't do this because you can't bind a reference-to-const
to a reference-to-non-const
.*
You could roll your own, but it makes more sense to just use std::swap
, which is designed explicitly for this purpose, and fully generic:
#include <algorithm>
std::swap(pi, pj);
[Live example]
* Because that would allow things like this:
int *p = something_non_const();
const int *q = something_really_const();
const int *&r = p;
r = q; // Makes p == q
*p = ...; // Uh-oh
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With