繁体   English   中英

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

[英]C++ map access discards qualifiers (const)

以下代码表示将映射作为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

std::mapoperator []未声明为const ,并且不能由于其行为:

T& operator[] (const Key& key)

返回对映射到与 key 等效的键的值的引用,如果此类键不存在,则执行插入。

因此,您的函数不能声明为const ,也不能使用映射的operator[]

std::mapfind()函数允许您在不修改映射的情况下查找键。

find()返回一个iterator ,或const_iteratorstd::pair同时含有键( .first )和值( .second )。

在 C++11 中,您还可以将at()用于std::map 如果元素不存在,该函数会抛出std::out_of_range异常,与operator []

由于operator[]没有 const 限定的重载,因此不能安全地用于 const 限定的函数中。 这可能是因为当前的重载是为了返回和设置键值而构建的。

相反,您可以使用:

VALUE = map.find(KEY)->second;

或者,在 C++11 中,您可以使用at()运算符:

VALUE = map.at(KEY);

您不能在const映射上使用operator[] ,因为该方法不是const因为它允许您修改映射(您可以分配给_map[key] )。 尝试改用find方法。

一些较新版本的 GCC 标头(我的机器上为 4.1 和 4.2)具有非标准成员函数 map::at(),它们被声明为 const 并在键不在映射中时抛出 std::out_of_range 。

const mapped_type& at(const key_type& __k) const

从函数注释中的引用来看,这似乎已被建议作为标准库中的新成员函数。

首先,您不应该使用以 _ 开头的符号,因为它们是为语言实现/编译器编写者保留的。 _map 很容易成为某人编译器上的语法错误,除了你自己之外,没有人可以责怪。

如果要使用下划线,请将其放在末尾,而不是开头。 您可能犯了这个错误,因为您看到一些 Microsoft 代码这样做。 请记住,他们编写自己的编译器,因此他们可能能够逃脱。 即便如此,这也是一个坏主意。

运算符 [] 不仅返回一个引用,它实际上在映射中创建了条目。 所以你不只是得到一个映射,如果没有,你正在创建一个。 那不是你想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM