Using std::map where V has no usable default constructor

后端 未结 9 1637
予麋鹿
予麋鹿 2020-12-05 13:11

I have a symbol table implemented as a std::map. For the value, there is no way to legitimately construct an instance of the value type via a default constructo

9条回答
  •  死守一世寂寞
    2020-12-05 13:29

    When you use an operator override in C++, it's best to stick as closely as possible with the semantics of the operator in the default case. The semantics of the default. operator[] is replacement of an existing member in an array. It would appear that std::map bends the rules a bit. That's unfortunate, because it leads to this sort of confusion.

    Note that the documentation (http://www.sgi.com/tech/stl/Map.html) for operator[] under std::map says:"Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object, operator[] inserts the default object data_type()."

    I'd suggest that you treat replacement and insertion differently. Unfortunately, this means you need to know which is required. That may mean doing a lookup on the map first. If performance is an issue, you might need to find an optimization where you can test for membership and insert with one lookup.

提交回复
热议问题