无法将参数从int *转换为const int *&
我确实了解const T *&是对const类型T的指针的引用.该指针具有低级const,因此它不会更改其指向的值.但是,以下代码在编译时失败,并给出以下消息:
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;
}
您无法执行此操作,因为您无法将对const
的引用绑定到对非const
的引用. sup> *
You can't do this because you can't bind a reference-to-const
to a reference-to-non-const
.*
您可以自己动手,但仅使用 std::swap
,它是为此目的而明确设计的,并且是完全通用的:
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);
[ 在线示例 ]
*因为这将允许这样的事情:
int *p = something_non_const();
const int *q = something_really_const();
const int *&r = p;
r = q; // Makes p == q
*p = ...; // Uh-oh