Using std shared_ptr as std :: map key

I wandered - can I use std::shared_ptr as the map key?

more specifically, the reference counter of the pointer may differ from the value that it had when assigning the card.

Will it be correctly identified on the map?

+7
c ++ std map key
source share
2 answers

Yes, you can. std::shared_ptr has an operator< defined in a way suitable for using a map key. In particular, only pointer values ​​are compared, not reference counting.

+7
source share

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

 #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= 
+9
source share

All Articles