指向常量对象的非常量指针的非常量引用
Non-const reference to a non-const pointer pointing to the const object
简单地说,我有一个简单的指针:
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;
}
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- OpenGL大的3D纹理(>2GB)非常慢
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 使用常量键但非常量值进行映射
- 为什么`is_open()`非常常量
- 从getter方法返回常量和非常量值
- 阻止const类函数在引用成员上调用非常常量类函数
- C++初始化非常大的常量数组,最佳实践
- 提高c++中非常大的常量的可读性