提升unordered_map - 错误或不当使用?

时间:2011-05-25 15:03:18

标签: c++ boost

我在boost :: unordered_map库(v1.45.0)中遇到了奇怪的行为。

在我班上我创建了一个对象:

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
}

当映射为空时,应用程序将中止调用“bufferStructMap.at(...)”,即使API说可以抛出的唯一异常是std :: out_of_range。

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

谢谢!

4 个答案:

答案 0 :(得分:1)

我宁愿抓住作为const参考

catch ( std::out_of_range const& e ){

答案 1 :(得分: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";
    }
}

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

答案 2 :(得分:1)

马克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

答案 3 :(得分:1)

请尝试std::out_of_range,而不是抓住std::exception。然后,您可以使用what成员获取有关异常的更多信息。