Reputation: 3934
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?
Upvotes: 27
Views: 19921
Reputation: 5102
Yes, you can... but be careful. operator<
is defined in terms of the pointer, not in terms of the pointed.
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=
Upvotes: 28
Reputation: 20993
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.
Upvotes: 27