2011-05-25 65 views
1

我从boost :: unordered_map库(v1.45.0)中得到了奇怪的行为。Boost unordered_map - 错误或不正确的用法?

在我的班级我创建一个对象:

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 
} 

当地图为空时,ap折叠放弃与调用“bufferStructMap.at(...)”,即使API说唯一可以抛出的异常是一个std :: out_of_range。

任何人都可以检测到我的代码有问题,或者这是一个提升错误?

谢谢!

+0

你知道你实际得到什么类型的异常吗?偶然得到了“bad_cast”吗? – 2011-05-25 15:06:18

+1

为什么static_cast? – 2011-05-25 15:13:13

+0

@尼尔:我想案子是没有必要的,我只是为了确保我确定的类型是正确的。但我肯定可以删除它。好的,删除了演员。问题仍然存在.. – 2011-05-25 15:15:04

回答

1

Mark B可能是对的。如果不是,它看起来像是Boost中的一个bug。

尽管...因为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 
+0

你说得对,这比使用例外来试图控制正常的程序流程要聪明得多。毕竟,例外是出于特殊情况。 – 2011-05-25 19:49:03

1

我宁愿赶上为const参考

catch (std::out_of_range const& e){ 
1

此代码有没有问题:

#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"; 
    } 
} 

所以我想你的问题是其他地方 - 你需要发布更多的代码。

1

而是抓住std::out_of_range,尽量std::exception。然后,您可以使用what成员获取有关该例外的更多信息。