Are mutable hashmap keys a dangerous practice?

后端 未结 7 1604
鱼传尺愫
鱼传尺愫 2020-11-22 06:58

Is it bad practice to use mutable objects as Hashmap keys? What happens when you try to retrieve a value from a Hashmap using a key that has been modified enough to change

7条回答
  •  独厮守ぢ
    2020-11-22 07:44

    As others explained, it is dangerous.

    A way to avoid that is to have a const field giving explicitly the hash in your mutable objects (so you would hash on their "identity", not their "state"). You might even initialize that hash field more or less randomly.

    Another trick would be to use the address, e.g. (intptr_t) reinterpret_cast(this) as a basis for hash.

    In all cases, you have to give up hashing the changing state of the object.

提交回复
热议问题