【发布时间】:2021-01-15 01:32:42
【问题描述】:
以下代码表示将映射作为const 传递给operator[] 方法会丢弃限定符:
#include <iostream>
#include <map>
#include <string>
using namespace std;
class MapWrapper {
public:
const int &get_value(const int &key) const {
return _map[key];
}
private:
map<int, int> _map;
};
int main() {
MapWrapper mw;
cout << mw.get_value(42) << endl;
return 0;
}
这是因为地图访问时可能发生的分配吗?不能将具有映射访问权限的函数声明为 const 吗?
MapWrapper.cpp:10: error: passing const std::map<int, int, std::less<int>,
std::allocator<std::pair<const int, int> > > as this argument of
_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)
[with _Key = int, _Tp = int, _Compare = std::less<int>,
_Alloc = std::allocator<std::pair<const int, int> >] discards qualifiers
【问题讨论】:
-
只是吹毛求疵,但 mw 可以简单地声明为 MapWrapper mw;
-
好点——我用几种语言写作,所以我倾向于规范它们的语法,这样它们都适合我的脑海。 :)
-
我很感激。不过要小心,在这种情况下,您有一个不必要的额外对象构造和分配。
-
另一个好点——依赖默认赋值运算符对于公共示例来说不是一个好习惯。 ;)