对非常量对象的常量引用
Constant Reference to Non-Const Object
发现很难理解为什么我不能对可变对象进行不可变引用?如果我像这样传递对容器的引用:
auto f(const map<int, int>& x) -> decltype(non-const map iterator) {...}
它认为x
是常量,我请求它的任何迭代器都是const_iterator
类型。
我想要以下内容(或者我是这么认为的(:auto f(map<int, int>& const x) -> decltype(non-const map iterator)
但它不编译。
这并不难解决,但我希望我的项目代码库在 const 方面有一些统一性。
长话短说,您无法以任何可靠的方式从const
std 容器中获取iterator
。
为了说明为什么会这样,请看一下容器是如何实现的。
template<typename T>
class map
{
struct node {
T data;
node *lchild, *rchild, *parent;
};
public:
iterator begin();
const_iterator begin() const;
private:
node* head;
};
容器由于其性质,需要以间接的方式处理恒常性。它们通常保存指向保存对象的内存的指针,使用const
限定容器只会影响指针及其方法。
// const map looks like
node* const head;
如果容器天真地返回一个iterator
,即使它被限定为const
,编译器不会抱怨,毕竟你没有在语法上改变容器中的任何内容。
// this is legal but wrong in a const map
head->data = T{};
// constness only prevents this
head = nullptr;
但是,由于容器在概念上是指针,而指针指向的内容,因此在使用const
限定时返回iterator
在语义上是错误的。为了解决这个问题,我们引入了const
过载,保证const
容器真正const
。
就map
而言,发出iterator
会立即破坏const
应该承受的合同。map
在发出iterator
后无法确保其恒定性,您可能会也可能不会用它改变内容。
相关文章:
- 什么时候在C++中返回常量引用是个好主意
- 通过常量引用传递参数的矩阵模板类
- 在C++中使用非常量引用作为常量
- 具有常量引用参数的函数模板专用化
- 多个"常量引用"变量可以共享同一个内存吗?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 为什么常量方法可以采用非常量引用?
- 为什么当我们有常量引用时创建临时对象?
- 如何返回向量的常量引用?
- C++:常量引用参数
- 不同于按值传递和常量引用传递的程序集
- 为什么const_cast和static_cast常量引用没有效果?
- C++ 获取函数在常量引用中按值返回的结果
- 从 BubbleSort* 类型的右值初始化 'AssortedSorter&' 类型的非常量引用无效"
- C++ 在类中使用常量引用文本时 O2 内存泄漏
- 是否可以跨 dll 边界返回常量引用/指向 std::vectors?
- C++中大多数/所有 setter 函数的参数是否应该写为常量引用?
- 通过非常量引用参数修改常量引用参数
- 将常量引用传递给线程
- 为什么C++中没有常量引用,就像常量指针一样?