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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/262853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:08:06  来源:igfitidea点击:

C++ map access discards qualifiers (const)

c++stlconstmaps

提问by cdleary

The following code says that passing the map as constinto the operator[]method discards qualifiers:

以下代码表示将 map as 传递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;
}

Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const?

这是因为地图访问中可能发生的分配吗?不能将具有映射访问的函数声明为 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

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

回答by luke

std::map's operator []is not declared as const, and cannot be due to its behavior:

std::map'soperator []未声明为const,并且不能是由于其行为:

T& operator[] (const Key& key)

Returns a reference to the value that is mapped to a key equivalent to key, performing insertion if such key does not already exist.

T& operator[] (const Key& key)

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

As a result, your function cannot be declared const, and use the map's operator[].

因此,您的函数不能被声明const,并使用地图的operator[].

std::map's find()function allows you to look up a key without modifying the map.

std::mapfind()功能允许您在不修改地图的情况下查找键。

find()returns an iterator, or const_iteratorto an std::paircontaining both the key (.first) and the value (.second).

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

In C++11, you could also use at()for std::map. If element doesn't exist the function throws a std::out_of_rangeexception, in contrast to operator [].

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

回答by Richard

Since operator[]does not have a const-qualified overload, it cannot be safely used in a const-qualified function. This is probably because the current overload was built with the goal of both returning and setting key values.

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

Instead, you can use:

相反,您可以使用:

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

or, in C++11, you can use the at()operator:

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

VALUE = map.at(KEY);

回答by nlativy

You cannot use operator[]on a map that is constas that method is not constas it allows you to modify the map (you can assign to _map[key]). Try using the findmethod instead.

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

回答by Nathan Kitchen

Some newer versions of the GCC headers (4.1 and 4.2 on my machine) have non-standard member functions map::at() which are declared const and throw std::out_of_range if the key is not in the map.

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

const mapped_type& at(const key_type& __k) const

From a reference in the function's comment, it appears that this has been suggested as a new member function in the standard library.

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

回答by Dov

First, you should not be using symbols beginning with _ because they are reserved to the language implementation/compiler writer. It would be very easy for _map to be a syntax error on someone's compiler, and you would have no one to blame but yourself.

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

If you want to use an underscore, put it at the end, not the beginning. You probably made this mistake because you saw some Microsoft code doing it. Remember, they write their own compiler, so they may be able to get away with it. Even so, it's a bad idea.

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

the operator [] not only returns a reference, it actually creates the entry in the map. So you aren't just getting a mapping, if there is none, you are creating one. That's not what you intended.

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