How can I use a std::map with std::weak_ptr as key?

C++11 provides appropriate mechanisms for comparisons of std::weak_ptr, namely: std::owner_less.

This should be the default for maps and sets. If the C++ compiler you are using is having a hard time, try using std::owner_less if it is available. If it is not available, you will need to provide a similar mechanism as std::owner_less so you can appropriately compare std::weak_ptr objects.


As explained in Jody Hagins' answer, you should use std::owner_less as comparison function object of an associative container if you use a std::weak_ptr as key. I'd like to expand on that answer by providing the following full solution for your code:

int main() {
    std::map<std::weak_ptr<int>, bool, std::owner_less<std::weak_ptr<int>>> myMap;

    std::shared_ptr<int> sharedptr(new int(5));
    std::weak_ptr<int> weakptr = sharedptr;

    myMap[weakptr] = true;

    return 0;
}

Since C++17 you can omit the template parameter for owner_less, resulting in shorter code as follows:

std::map<std::weak_ptr<int>, bool, std::owner_less<>> myMap;

And if you plan to use a weak_ptr to a custom class instead of an int, then you can simply replace the int by the name of your class as shown in this example code on Coliru.

In general, apart from providing a proper comparison function (or overloading operator<) for a (custom) key type, nothing needs to be done for a std::map. Overloading operator== for the key type is not required.