In MatcherCast, store the input value as its own type rather than as the Matcher type, to avoid dangling references

PiperOrigin-RevId: 769240838
Change-Id: I7b1ac23a0a88ba90b5d1ae6e20b97f679f381f31
This commit is contained in:
Abseil Team
2025-06-09 12:06:24 -07:00
committed by Copybara-Service
parent 28e9d1f267
commit 6230d316e1
3 changed files with 72 additions and 18 deletions

View File

@@ -622,15 +622,42 @@ struct IntReferenceWrapper {
const int* value;
};
// Compared the contained values
bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
return a.value == b.value;
return *a.value == *b.value;
}
TEST(MatcherCastTest, ValueIsNotCopied) {
int n = 42;
Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
// Verify that the matcher holds a reference to n, not to its temporary copy.
EXPECT_TRUE(m.Matches(n));
TEST(MatcherCastTest, ValueIsCopied) {
{
// When an IntReferenceWrapper is passed.
int n = 42;
Matcher<IntReferenceWrapper> m =
MatcherCast<IntReferenceWrapper>(IntReferenceWrapper(n));
{
int value = 42;
EXPECT_TRUE(m.Matches(value));
value = 10;
EXPECT_FALSE(m.Matches(value));
// This changes the stored reference.
n = 10;
EXPECT_TRUE(m.Matches(value));
}
}
{
// When an int is passed.
int n = 42;
Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
{
int value = 42;
EXPECT_TRUE(m.Matches(value));
value = 10;
EXPECT_FALSE(m.Matches(value));
// This does not change the stored int.
n = 10;
EXPECT_FALSE(m.Matches(value));
}
}
}
class Base {