google / googlemock

Google Mock
427 stars 204 forks source link

Matching std::reference_wrapper objects with RefMatcher yields SEH exceptions or undefined behavior #218

Open metallermartin opened 5 years ago

metallermartin commented 5 years ago

The test below yields undefined behavior or access violations using VS2017 Version 15.9.2.

It seems that the ref matcher tries to compare addresses of the std::reference_wrapper objects themselves instead of comparing the adresses of the objects referenced by the std::reference_wrapper.

struct Object
{
  int id;
};

std::ostream & operator<<(std::ostream & strm, Object const & object)
{
  return strm << "of type Object with id " << object.id;
}

struct Dummy
{
  explicit Dummy(int i)
    : object{i}
  {}

  Object object;
};

TEST(Reference_Wrapper, MatcherBug)
{
  Dummy dummy1{1};
  Dummy dummy2{2};
  Dummy dummy3{3};
  std::vector<std::reference_wrapper<Object>> objects{ dummy1.object, dummy2.object, dummy3.object };
  EXPECT_THAT(objects[0], Ref(dummy1.object));
  EXPECT_THAT(objects[1], Ref(dummy2.object));
  EXPECT_THAT(objects[2], Ref(dummy3.object));
  EXPECT_THAT(objects, ElementsAre(Ref(dummy1.object), Ref(dummy2.object), Ref(dummy3.object)));
};