以下代码表示将map传递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;
}
Run Code Online (Sandbox Code Playgroud)
这是因为地图访问中可能出现的分配吗?没有地图访问的函数可以声明为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 :: string的getter方法.像这样的东西例如:
class foo
{
private:
std::string name_;
public:
std::string name()
{
return name_;
}
};
Run Code Online (Sandbox Code Playgroud)
当然吸气者会更好地回归const std::string&?当前方法返回的副本效率不高.会返回一个const引用会导致任何问题吗?