0

I have a code which looks as follows

template <typename KeyType, typename ValueType>
KeyType IDSystem<KeyType,ValueType>::registerParameter(const ValueType& value)
{
    KeyType key = __IDCounter++;
    _Map[key] = value; //crashes here
    return key;
}

where _Map is

std::map<KeyType, ValueType> _Map;

The program used to crash where indicated, and then I replaced that line with

_Map.at(key) = value; //out_of_range thrown here

And now the program throws an std::out_of_range exception at that same line...

KeyType is int64_t from the standard library, and ValueType is a pointer to some class (like MyClass*).

The surprising part is that I used std::map just like that before... and no problem occured.

Am I using std::map incorrectly? Please advise.

The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189

4 Answers4

3

You might want to use find instead of the [] operator, because it returns a past-the-end iterator if you try to access a non-existent key.

Regarding your code, please take the time to post a SSCCE, because I can't see anything wrong in the few lines of code above.

Mihai Todor
  • 8,014
  • 9
  • 49
  • 86
3

The problem wasn't in the map. The pointer to this class wasn't initialized correctly, and that caused the pro blem.

Thank you for all your efforts, and sorry for the misleading question.

The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189
1

The code as written (aside from the underscore names that probably aren't hurting anything) is fine, so the problem is most likely elsewhere. In particular, if the free store has been corrupted (by deleting a pointer that wasn't new'ed, or by running off the end of an allocated block), the symptoms can show up pretty much anywhere that the free store is used. map::operator[] uses the free store when you give it a key that isn't already in the map, so I suspect that that's the problem: something else has blown up the heap.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
1

The out_of_range exception is a read herring and is a different problem to your original crashing problem.

The problem is when you do:

_Map[key] = value;

So you are doing an assignment.
This suggests that you have a bad assignment operator (or something you are doing in the assignment operator is hitting some other bad code).

Since we have no idea what ValueType is we can not diagnose the problem beyond this point. I could suggest that you check that you are implementing the rule of 3(5) correctly.

If you provide the definition of ValueType and its assignment operator we may be able to help further. Usually for this type of problem it is best to reduce the problem to the smallest compilable example that you can that generates the problem and post that.

Martin York
  • 257,169
  • 86
  • 333
  • 562