繁体   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