Using std shared_ptr as std::map key

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=

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.

Tags:

C++

Key

Map

Std