为什么C ++ const引用可以归类为非const引用 [英] Why can C++ const references be collasped into non-const references
问题描述
考虑以下C ++程序:
Consider the following C++ program:
#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。这表明返回了看似const引用实际上,通过get()获得的是非const 引用,因为它允许修改其引用的值。
The program compiles OK and outputs 43. This suggests that the seemingly const reference returned by get() is in fact a non-const reference, because it allows to modifies the value it refers to.
这是规则吗?
如何强制执行get()返回的引用的行为类似于const引用,即不允许修改
How to enforce that the reference returned from get() behaves like a const reference, that is, it doesn't allow to modify the value it refers to?
推荐答案
引用规则折叠会导致这种行为吗?
Is it a rule of reference collapsing that causes this behaviour?
是。您有:
T = int&
const T& = const (int&) &
引用不能为 const
(您仍然无法重新绑定它们,因此将其忽略),对引用的引用只是引用。
References can't be const
(you can't rebind them anyways, so it's ignored) and a reference to a reference is just a reference.
所以您拥有
const T& = int&
要解决此问题,您需要应用 const
到基础类型,您可以通过删除引用来实现:
To fix this, you need to apply const
to the underlying type, which you can do like this by removing the reference:
const std::remove_reference_t<T>& get() { return x_; }
// ^^^^^^^^^^^^^^^^^^^^^^^
这篇关于为什么C ++ const引用可以归类为非const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!