簡體   English   中英

提升 unordered_map - 錯誤或使用不當?

[英]Boost unordered_map - bug or improper usage?

我從 boost::unordered_map 庫(v1.45.0)中得到了奇怪的行為。

在我的 class 中,我創建了一個 object:

boost::unordered_map<uint16, MyStruct *> bufferStructMap;

然后我在構造函數初始化列表中對其進行初始化:

 MyClass::MyClass () : bufferStructMap( ) { .... } 

然后我嘗試使用“ at ”方法從中提取一些東西(參見鏈接中的 API):

const uint16 bufferNumber = 1;
try {

    MyStruct * ptr = ( this->bufferStructMap.at( bufferNumber ) );
}
catch ( std::out_of_range & e ){

  //deal with exception
}

當 map 為空時,應用程序通過調用“bufferStructMap.at(...)”中止,即使 API 說唯一可以拋出的異常是 std::out_of_range。

任何人都可以檢測到我的代碼有問題,還是這是一個提升錯誤?

謝謝!

我寧願作為 const 參考

catch ( std::out_of_range const& e ){

這段代碼沒有問題:

#include "boost/unordered_map.hpp"
#include <exception>
#include <iostream>

struct MyStruct {};
boost::unordered_map<int, MyStruct *> bufferStructMap;

int main() {
    try {
        MyStruct * ptr = (bufferStructMap.at( 1 ) );
    }
    catch ( std::out_of_range & e ){
      std::cout << "caught\n";
    }
}

所以我猜你的問題出在其他地方 - 你需要發布更多代碼。

馬克 B 可能是對的。 如果不是,它看起來像 Boost 中的一個錯誤。

雖然...由於 std::tr1::unordered_map(以及 C++0x 版本?不確定)不提供 at(),您可能只想使用 find()。

// Save typing, allow easy change to std::unordered_map someday
typedef boost::unordered_map<uint16, MyStruct *> map_t;

map_t bufferStructMap;

...

map_t::const_iterator p = bufferStructMap.find(bufferNumber);
if (p == bufferStructMap.end())
    // not found
else
    // p->second is your value

不要捕獲std::out_of_range ,而是嘗試std::exception 然后您可以使用what成員來獲取有關異常的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM