Search code examples
c++dictionarykeystd

Using std shared_ptr as std::map key


I was wandering - can I use std::shared_ptr as a map key?

more specifically - the reference counter of the pointer might be different from the value it had when assigned to the map.

Will it be correctly identified in the map?


Solution

  • Yes you can. std::shared_ptr has operator< defined in a way appropriate for map key usage. Specifically, only pointer values are compared, not reference counts.

    Obviously, the pointed objects are not part of the comparison. Otherwise one could easily make the map invalid by modifying a pointed object and making the order in the map inconsistent with the comparison.