Using std shared_ptr as std::map key

14,872

Solution 1

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.

Solution 2

Yes, you can... but be careful. operator< is defined in terms of the pointer, not in terms of the pointed.

#include <memory>
#include <map>
#include <string>
#include <iostream>

int main() {

    std::map<std::shared_ptr<std::string>,std::string> m;

    std::shared_ptr<std::string> keyRef=std::make_shared<std::string>("Hello");
    std::shared_ptr<std::string> key2Ref=std::make_shared<std::string>("Hello");

    m[keyRef]="World";

    std::cout << *keyRef << "=" << m[keyRef] << std::endl;
    std::cout << *key2Ref << "=" << m[key2Ref] << std::endl;

}

prints

Hello=World
Hello=
Share:
14,872

Related videos on Youtube

sara
Author by

sara

Updated on July 08, 2022

Comments

  • sara
    sara almost 2 years

    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?

  • tomjakubowski
    tomjakubowski over 6 years
    Note that if you use the "aliasing constructor" of std::shared_ptr, depending on your use case you may want to consider using std::owner_less as the map's comparison functor. This will get you ordering based on the pointer to the whole object, rather than the subobject directly pointed to by the shared_ptr.