Is there a possibility to compare two maps containing std::unique_ptr
s?
In my specific case, I want to compare two maps containing tuples of std::unique_ptr
(The std::tuple
part is not relevant to the question, but I think it is important to consider the complexity induced by using heterogeneous types when manually implementing the most basic operations, like comparison).
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);
}
Obviously, when I run the above test (using Google Test), the test will fail, because the addresses are compared, instead of values (for which operator==
and operator!=
are provided).
Actual: { (1, (2, 4-byte object <B8-BF 86-01>)) }
Expected: map1
Which is: { (1, (2, 4-byte object <A0-BC 86-01>)) }
[FAILED]
I can manually iterate over each pair and de-reference each object, but I wonder if there is a more standardized solution for unique_ptr
, given the fact that it is a basic construct.