繁体   English   中英

非const引用指向const对象的非const指针

[英]Non-const reference to a non-const pointer pointing to the const object

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

int* a;

现在,我想改变这个指针的值。 我想在一个函数中这样做。 函数确保它不会改变指针指向的对象,但会改变指针本身。 这就是为什么我希望这个函数接受如下参数:非const引用(因为指针的值将被改变)到指向const对象的非const指针(指针本身可以改变)(函数保证,该对象,指针指向不会被改变)。

最简单的功能是:

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

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

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

编译器不满意并说:

从'const int *'函数(a)的rvalue初始化'const int *&'类型的非const引用;

我不太明白这个错误,因为对我来说没有涉及rvalue(我传递对象的引用,已经存在于堆栈中。)

问题是,我该怎么做呢?

可以在此处找到示例: https//ideone.com/D45Cid


编辑:

有人建议,我的问题是为什么将“指向非const的指针”转换为“指向const的指针”是不合法的。

我的问题是不同的,因为我没有使用指针指针我只使用指向对象/值的指针并存储对它的引用,因此情况就像在回答这个问题:

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

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

此外,我质疑这个问题的完美和干净的解决方案,这个问题没有涉及

我不太明白这个错误,因为对我来说没有涉及rvalue(我传递对象的引用,已经存在于堆栈中。)

int*const int*是不同的东西。 当你传递a类型的int*function(const int*&)它需要被隐式强制转换为const int*首先,这是暂时的,即右值,不能被绑定到非const referece。 这就是编译器抱怨的原因。

问题是,我该怎么做呢?

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

我不太确定你想要实现的目标。

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

#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的评论。

我能看到使用“非常规引用”到“const int”的“非常量指针”的唯一方法是使用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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM