为什么C++常量引用可以折叠为非常量引用
Why can C++ const references be collasped into non-const references
请考虑以下C++程序:
#include <iostream>
template<typename T>
class A
{
public:
explicit A(T& x) : x_(x){}
const T& get() { return x_; }
private:
T x_;
};
int main()
{
int x = 42;
A<int&>(x).get() = 43; // compiles fine, even though get() looks like it returns a const ref
std::cout << x << 'n';
}
程序编译 OK 并输出 43。这表明 get(( 返回的看似常量引用实际上是一个非常量引用,因为它允许修改它引用的值。
是导致这种行为的参考规则崩溃吗?
如何强制从 get(( 返回的引用的行为类似于 const 引用,也就是说,它不允许修改它引用的值?
是导致这种行为的参考规则崩溃吗?
是的。你有:
T = int&
const T& = const (int&) &
引用不能const
(无论如何都不能重新绑定它们,所以它被忽略(,对引用的引用只是一个引用。
所以你有
const T& = int&
若要解决此问题,需要将const
应用于基础类型,可以通过删除引用来执行此操作:
const std::remove_reference_t<T>& get() { return x_; }
// ^^^^^^^^^^^^^^^^^^^^^^^
相关文章:
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 为什么我可以通过引用修改常量返回
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 将常量指针引用绑定到非常量指针
- 通过常量引用传递参数的矩阵模板类
- 按值捕获引用时出现非常量
- 在C++中使用非常量引用作为常量
- 具有常量引用参数的函数模板专用化
- 多个"常量引用"变量可以共享同一个内存吗?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 为什么按值传递QStringView比引用常量更快?
- 通过引用常量函数调用另一个类的非常量函数
- 构造常量对象与引用常量对象
- 引用“常量value_type”时出错
- 为什么可以在 for 语句中重新分配引用常量
- 程序反馈:命名循环索引和引用常量数据
- 堆还是栈?在c++中函数调用中引用常量字符串时
- 为什么常量结构数组在按名称引用常量结构时不放在 .rodata 中?
- 为什么编译器允许在函数中发送对迭代器的引用,该函数引用常量迭代器