相关疑难解决方法(0)

C++ map访问丢弃限定符(const)

以下代码表示将map传递constoperator[]方法会丢弃限定符:

#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 …

c++ maps stl const

106
推荐指数
4
解决办法
4万
查看次数

返回对象的const引用而不是副本

虽然重构了一些代码,但我遇到了一些返回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引用会导致任何问题吗?

c++ const

70
推荐指数
5
解决办法
10万
查看次数

标签 统计

c++ ×2

const ×2

maps ×1

stl ×1