Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert argument from int * to const int *&

Tags:

c++

pointers

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;
}
like image 725
Yukine Tokisaki Avatar asked Sep 04 '25 17:09

Yukine Tokisaki


1 Answers

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

like image 182
Oliver Charlesworth Avatar answered Sep 07 '25 05:09

Oliver Charlesworth