开发者

Boost unordered_map - bug or improper usage?

I am getting strange behavior from within the boost::unordered_map library (v1.45.0).

In my class I create an object:

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

Then I initialize it in the constructor initialization list:

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

Then I try to pull something out of it using the method "at" (see API in link):

const uint16 bufferNumber = 1;
try {

    MyStruct * ptr = ( this->bu开发者_开发百科fferStructMap.at( bufferNumber ) );
}
catch ( std::out_of_range & e ){

  //deal with exception
}

When the map is empty, the application aborts with the call to "bufferStructMap.at( ... )", even though the API says the only exception that can be thrown is a std::out_of_range.

Can anyone detect a problem with my code, or is this a boost bug?

Thanks!


Mark B is probably right. If not, it looks like a bug in Boost.

Although... Since std::tr1::unordered_map (and the C++0x version? not sure) does not provide at(), you might want to just use 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


I would rather catch as const reference

catch ( std::out_of_range const& e ){


This code has no problems:

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

So I guess your problem is somewhere else - you need to post more code.


Instead of catching std::out_of_range, try std::exception. Then you can use the what member to get more information about the exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜