指向常量对象的非常量指针的非常量引用

Non-const reference to a non-const pointer pointing to the const object

本文关键字:常量 非常 引用 指针 对象      更新时间:2023-10-16

简单地说,我有一个简单的指针:

int* a;

现在,我想更改这个指针的值。我想在函数中执行此操作。函数确保它不会更改指针指向的对象,但会更改指针本身。这就是为什么我希望这个函数采用这样的参数:非常量引用(因为指针的值会改变)到指向常量对象的非常量指针(指针本身可以改变)(函数确保指针指向的对象不会改变)。

最简单的功能是:

void function(const int*& a){
    a = 0;
}

但是当我尝试调用这个函数时:

int main(){
    int* a;
    function(a);
    return 0;
}

编译器不高兴,说:

"const int*&"类型的非常量引用的初始化无效来自"const int*"类型的右值函数(a);

我不能完全理解这个错误,因为对我来说,没有涉及右值(我正在传递对对象的引用,该对象已经存在于堆栈中。)

问题是,我如何才能正确地做到这一点?

示例如下:https://ideone.com/D45Cid


编辑:

有人建议,我的问题类似于"为什么不是";转换";指向非常数的指针的指针";至";指针到指针到常量";

我的问题不同,因为我不使用指向指针的指针,我只使用指向对象/值的指针并存储对它的引用,因此情况与该问题的答案类似:

const char c = 'c';
char* pc;
const char** pcc = &pc;   // not allowed
*pcc = &c;
*pc = 'C';                // would allow to modify a const object

在我的情况下是不可能的,因为我不能取消引用顶级指针(我没有这样的指针)。

此外,我还询问了这个问题的漂亮而干净的解决方案,

问题中没有涉及到这一点

我不能完全理解这个错误,因为对我来说,没有涉及右值(我正在传递对对象的引用,该对象已经存在于堆栈中。)

CCD_ 1和CCD_。当您将类型为int*a传递给function(const int*&)时,需要首先将其隐式转换为const int*,这是临时的,即右值,不能绑定到非常量引用。这就是编译器抱怨的原因。

问题是,我如何才能正确地做到这一点?

您可以更改a的类型或function()的参数类型,使它们完全匹配(如果不更改指针指向的值,则可能为const int*),以避免隐式转换和临时变量。或者,正如@TartanLlama所建议的,从int*0返回指针的新值。

我不太确定你想要实现什么。

不过,这段代码可能会对您有所帮助。它应该指向你如何做你想做的事。

#include <iostream>
using namespace std;
int A = 1;
int B = 2;
int C = 3;
void change_pointer(int*& a){
    // your pointer will point to B
    a = &B;
}
void change_value(int* const& a) {
    // the reference to pointer is constant, but not the value
    // a=&C; wouldn't work
    *a = C;
}
int main(){
    int* a;
    // at this point a is an undefined pointer to an int
    // *a is unallocated space
    a=&A; // you initialize the pointer with an other pointer
    cout << "*a = " << *a << ", A = " << A << ", B = " << B << ", C = " << C << endl;
    change_pointer(a); // makes 'a' point to B
    cout << "*a = " << *a << ", A = " << A << ", B = " << B << ", C = " << C << endl;
    change_value(a); // changes the value pointed by a to C (in the process modifying the value of B)
    cout << "*a = " << *a << ", A = " << A << ", B = " << B << ", C = " << C << endl;
    return *a;
}

编辑:作为对TartanLlama评论的回应。

我能看到的唯一方法是使用typedef:

#include <iostream>
using namespace std;
typedef const int const_int_t;
const_int_t A = 1;
const_int_t B = 2;
void change_pointer(const_int_t*& a){
    // your pointer will point to B
    a = &B;
}
int main(){
    const_int_t* a;
    a=&A; // you initialize the pointer with an other pointer
    cout << "*a = " << *a << ", A = " << A << ", B = " << B << endl;
    change_pointer(a); // makes 'a' point to B
    cout << "*a = " << *a << ", A = " << A << ", B = " << B << endl;
    return *a;
}