簡體   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