比较unique_ptr的映射
Compare maps of unique_ptr
是否有可能比较包含std::unique_ptr
s的两个映射?
在我的具体情况下,我想比较两个包含std::unique_ptr
元组的映射(std::tuple
部分与问题无关,但我认为在手动实现最基本的操作(如比较)时,考虑使用异构类型所引起的复杂性是很重要的)。
class MyObject
{
public:
bool operator==(const MyObject& other) const
{
return member1 == other.member1;
}
bool operator!=(const MyObject& other) const;
private:
std::string member1 = "specific string";
};
TEST(General, CompareMapOfTuplesOfUniquePtrs)
{
using MyType = std::map<int32_t, std::tuple<int32_t, std::unique_ptr<MyObject>>>;
MyType map1;
MyType map2;
map1.insert({ 1, std::make_tuple(2, std::make_unique<MyObject>()) });
map2.insert({ 1, std::make_tuple(2, std::make_unique<MyObject>()) });
ASSERT_EQ(map1, map2);
}
显然,当我运行上述测试(使用GoogleTest)时,测试将失败,因为比较的是地址,而不是值(提供了operator==
和operator!=
)。
Actual: { (1, (2, 4-byte object <B8-BF 86-01>)) }
Expected: map1
Which is: { (1, (2, 4-byte object <A0-BC 86-01>)) }
[FAILED]
我可以手动迭代每个对并取消引用每个对象,但我想知道unique_ptr
是否有一个更标准化的解决方案,因为它是一个基本的构造。
我能想到的最标准的解决方案就是为元组定义自己的等式运算符:
bool operator==( const std::tuple<int32_t, std::unique_ptr<MyObject>> & a,
const std::tuple<int32_t, std::unique_ptr<MyObject>> & b )
{
return std::get<0>(a) == std::get<0>(b) && *std::get<1>(a) == *std::get<1>(b);
}
这个示例可能对您来说已经足够了,除非您还想处理nullptr
。如果您对其他元组使用相同的模式,那么将其模板化可能是有意义的:
template < class A, class B >
bool operator==( const std::tuple<A, std::unique_ptr<B>> & a,
const std::tuple<A, std::unique_ptr<B>> & b )
{
return std::get<0>(a) == std::get<0>(b) && *std::get<1>(a) == *std::get<1>(b);
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 在未初始化映射的情况下,将值插入到映射的映射中
- QT通过C++添加映射QML项目
- 在c++中访问int到类对象的映射时出错
- 在C++中搜索嵌套多映射值
- 错误处理.将系统错误代码映射到泛型
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- std::哈希表示无序映射中的唯一 PTR
- 将内存数据PTR映射到qt输入字段
- 插入无序映射将共享ptr变为null