我在 map 中使用弱指针作为键。然而,当我尝试编译时,我得到了丑陋的消息,我将其解释为我缺少 std::weak_ptr 的比较运算符,这显然是 std::map 所必需的,因为它根据以下命令对其元素进行排序键值。
但是,现在 weak_ptr 类是一个智能指针类型类,因此可以使用指向某些托管数据的指针。
这个类不提供 operator< 方法的基本实现有充分的理由吗?我的意思是,比较指针值对我来说似乎很明显,而且,如果需要它以不同的方式工作,那么应该能够扩展或重新定义该方法以获得预期的行为,而不是'是吗?
在这里,您的见解将不胜感激。
感谢期待。
std::owner_less
是将智能指针排序为映射中的键的正确方法。
#include <map>
#include <memory>
#include <string>
struct Foo
{
};
using my_key = std::weak_ptr<Foo>;
using my_comp = std::owner_less<my_key>;
int main()
{
auto m = std::map<my_key, std::string, my_comp>();
auto p = std::make_shared<Foo>();
auto p1 = std::make_shared<Foo>();
m.emplace(p, "foo");
m.emplace(p1, "bar");
p.reset();
p1.reset();
}