Search code examples
c++stlsetshared-ptrunordered-set

Is it safe to modify shared_ptr in an (unordered_)set?


Elements stored in a set or unordered_set are immutable. If one changes an element that is stored in a set this may lead to the set not working properly anymore. However, does this include the pointed-to object when storing shared_ptr in a set?

As far as set is concerned it uses less() to compare two objects. The result should not change if the pointed to object changes or if the ref count changes. So I would understand that it is totally safe to have a set of shared_ptr and modify the pointed-to objects.

However, since unordered_set uses hash() to calculate the hash of its elements, which is equivalent to calling hash() on the pointed-to object of a shared_ptr, modifying the pointed-to object would get us into trouble.

Is this correct?


Solution

  • hash() for a smart pointer is equivalent to hash() for the pointer value, but hash() for the pointer value depends only on the pointer, not on the pointee. So you are safe to modify objects in the container - hash function results will not be changed.