为什么 STL 容器适配器堆栈中的 top 返回常量引用?

Why does top in the STL container adaptor stack return a const reference?

本文关键字:返回 top 常量 引用 STL 适配器 堆栈 为什么      更新时间:2023-10-16

容器适配器的规范stacktop应返回const引用。 为什么?

同样的问题也发生在queuefrontback上。 我可以看到在priority_queue的情况下,可修改的访问可能会弄乱优先级,从而弄乱"类不变性",但我不知道为什么你不能修改stackfrontbackqueuetop

该规范最实用的代理是 cppreference.com: 返回页首

你可以看到它返回一个const_reference,这是对适应的基础容器所持有的值的const引用。

为什么 STL 容器适配器中的topstack返回const引用?

因为该成员函数是常量限定的,并且容器适配器传播恒常性。

有一个非常量限定的重载返回可变引用。

常量重载存在的原因是,您可以访问常量堆栈的顶部元素。

引用最新标准草案:

[stack.defn]

reference         top()             { return c.back(); }
const_reference   top() const       { return c.back(); }