对指针行为不符合预期行为的 const 引用
const reference to a pointer not behaving as expected
为什么我在运行这个时会出现错误?我预计ptr_ref无法修改 ptr 指向的地址,但事情似乎没有按计划进行。
int b = 3;
int* ptr = &b;
//says something about cannot convert int* to type const int*&
const int*& ptr_ref = ptr;
提前感谢,15岁的C++菜鸟
ptr_ref
不是const
对指向int
的指针的引用,而是对指向const int
的指针的引用,因此类型不匹配。你必须做
int* const& ptr_ref = ptr;
问题是类型不匹配,因此无法创建引用。
int b = 3;
int* ptr = &b;
int*& ptr_ref = ptr;
是合法的。
int b = 3;
const int* ptr = &b;
const int*& ptr_ref = ptr;
是合法的。
int b = 3;
int* ptr = &b;
const int*& ptr_ref = ptr;
是不匹配的。
G++ 的错误消息可能对您有所帮助:
error: invalid initialization of non-const reference of type 'const int*&' from an rvalue of type 'const int*'
const int*& ptr_ref = ptr;
^
从本质上讲,它必须为此表达式创建一个const int*
,这是一个右值(本质上是一个临时对象),因此您无法保留对它的引用。更简单的表达方式是,你不能做你写的东西,原因与这是非法的相同:
int& added = 3 + 2;
根据您的情况,您只需删除参考名称即可解决此问题。大多数编译器将输出带有或不带有它的相同程序集,至少在优化时是这样,因为它们能够找出变量名只是一个别名的事实。
甚至在某些情况下,引用可能会表现得更糟,根据您的意图,可能值得了解 - 当我发现时,我很惊讶地知道它。
引用
本质上是常量,因此将其定义为int *& const ptr_ref = ptr
当你谈论常量引用时,它通常意味着对常量引用,这是你在问题中使用的定义。
[编辑] 编辑了我的答案,因为我错误地将 const 放在了 & 符号的错误一侧 - C++不会原谅你 [/edit]
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 如何在构造函数中传递 const 引用时强制编译器不接受右值
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- 对临时对象的Const引用不会延长其生存期
- 对 const 引用参数使用默认值会导致崩溃
- 在运算符重载中使用带有 const 引用的 friend 函数
- C++通过 const 引用传递时不调用派生类函数
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 为什么要返回对小类成员的 const 引用?
- C - 最好将枚举类作为值或const引用
- RVO:返回由值传递的值,即使显式分配给 const 引用也是如此
- const引用与可变成员的对象
- 每当传递lvalue时,每当通过rvalue传递时,将const引用存储
- 对类成员而不是 getter 的 Const 引用
- 从类型 'Matrix&' 的右值初始化 类型的非 const 引用无效 'Matrix'
- 在函数中使用 const 引用参数访问函数中成员的最佳实践 C++.
- STD ::配对的const引用如何工作
- 为什么我的C 函数拒绝返回const引用