使用std shared_ptr作为std::map键

Using std shared_ptr as std::map key

本文关键字:std map 作为 ptr shared 使用      更新时间:2023-10-16

我在徘徊-我可以使用std::shared_ptr作为映射键吗?

更具体地说,指针的引用计数器可能与它赋值给map时的值不同。

它会在地图上被正确地识别吗?

是的,你可以…但是要小心。operator<是根据指针定义的,而不是根据指向定义的。

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;
}

打印

Hello=World
Hello=

可以。std::shared_ptr以适合映射键使用的方式定义了operator<。具体来说,只比较指针值,不比较引用计数。

显然,指向对象不是比较的一部分。否则,通过修改指向对象并使映射中的顺序与比较不一致,很容易使映射无效。