无法将int*参数转换为const int *&

4

我知道const T*&是指向常量类型T的指针引用。该指针具有低级const,因此它不会改变其指向的值。然而,以下代码在编译时失败,并给出以下消息:

error C2664: 'void pointer_swap(const int *&,const int *&)': cannot convert argument 1 from 'int *' to 'const int *&'.

有没有一种方法可以在函数中修改指针但防止指向的值发生变化?
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;
}

1
你有一个 int*,需要一个 const int* 作为输入。将 pi 和 pj 更改为 const int* 可以解决错误。但我不确定为什么没有从非 const 到 const 的隐式转换。 - Hayt
1
@Hayt - 因为这是一个引用。它将允许函数执行类似 pi = &something_that_really_is_const; 的操作,这将允许调用者修改 something_that_really_is_const - Oliver Charlesworth
3个回答

4

您不能这样做,因为您不能将一个指向非const的引用绑定到一个指向const的引用。*

您可以自己编写代码实现此功能,但更明智的做法是使用std::swap,该函数专门为此目的设计,具有完全通用性:

#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


0
在主函数中将pi和pj声明为常量。
#include <iostream>
using namespace std;

void pointer_swap(const int *&pi, const int *&pj)
{
    const int *ptemp = pi;
    pi = pj;
    pj = ptemp;
}

int main()                                                                
{                                    
    int i = 1, j = 2;                
    const int *pi = &i, *pj = &j;          
    pointer_swap(pi, pj);
    return 0;
}

1
你能否为一个完整的答案解释一下这是为什么吗? - Hayt
@Hayt现在我看到你在评论中也提出了同样的解决方案。我的错 > :( - Undefined Behaviour
我之所以没有将其作为答案是因为在那时我无法想出为什么。如果您愿意,可以添加解释。 - Hayt
这个函数现在不能与int *一起工作了。一个模板化的解决方案可以很好地泛型化这个问题。 - Oliver Charlesworth

0

这是我的想法。希望能够帮助到你。

void fun1(const int * p) 
{
}

int * pa = 0;
fun1(pa); //there is implicit conversion from int * to const int *

void fun2(const int & p)
{

}
int a = 0;
fun2(a); //there is implicit conversion from int & to const int &.

这两个例子都表明编译器将帮助我们将当前类型转换为const当前类型。因为我们告诉编译器参数是const。

现在,看看这个:

void fun3(const int * &p) 
{
//this declaration only states that i want non-const &, it's type is const int * .
}

int *pi = 0;
fun3(pi); // error C2664

如果你希望进行从非const到const的隐式转换是不会发生的,因为函数声明仅声明了我想要非const &,其类型为const int *。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接