Add utilities to facilitate correct usage of rtc::RefCounted classes.

We have a few places where RefCountedObject is a class that's inherited
from, whereas it's meant to be the 'final' class. We also have many
places with RefCountedObject boilerplate code that has been copy pasted
around but FinalRefCountedObject might be a better fit for the
implementation. Then there's the fact that it would be nice to reduce the
amount of required boilerplate code.

Bug: webrtc:12701
Change-Id: I0aaf55197c8640b1b17d20c7c15c8d0bb3605161
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/215928
Reviewed-by: Mirko Bonadei <mbonadei@webrtc.org>
Commit-Queue: Tommi <tommi@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#33815}
This commit is contained in:
Tomas Gunnarsson
2021-04-22 17:41:33 +02:00
committed by Commit Bot
parent e6de5ae2d6
commit d7842008ef
3 changed files with 173 additions and 1 deletions

View File

@ -64,6 +64,20 @@ class RefClassWithMixedValues : public RefCountInterface {
std::string c_;
};
class Foo {
public:
Foo() {}
Foo(int i, int j) : foo_(i + j) {}
int foo_ = 0;
};
class FooItf : public RefCountInterface {
public:
FooItf() {}
FooItf(int i, int j) : foo_(i + j) {}
int foo_ = 0;
};
} // namespace
TEST(RefCountedObject, HasOneRef) {
@ -111,4 +125,42 @@ TEST(FinalRefCountedObject, CanWrapIntoScopedRefptr) {
EXPECT_TRUE(ref2->HasOneRef());
}
// This test is mostly a compile-time test for scoped_refptr compatibility.
TEST(RefCounted, SmartPointers) {
// Sanity compile-time tests. FooItf is virtual, Foo is not, FooItf inherits
// from RefCountInterface, Foo does not.
static_assert(std::is_base_of<RefCountInterface, FooItf>::value, "");
static_assert(!std::is_base_of<RefCountInterface, Foo>::value, "");
static_assert(std::is_polymorphic<FooItf>::value, "");
static_assert(!std::is_polymorphic<Foo>::value, "");
// Check if Ref generates the expected types for Foo and FooItf.
static_assert(std::is_base_of<Foo, Ref<Foo>::Type>::value &&
!std::is_same<Foo, Ref<Foo>::Type>::value,
"");
static_assert(std::is_same<FooItf, Ref<FooItf>::Type>::value, "");
{
// Test with FooItf, a class that inherits from RefCountInterface.
// Check that we get a valid FooItf reference counted object.
auto p = make_ref_counted<FooItf>(2, 3);
EXPECT_NE(p.get(), nullptr);
EXPECT_EQ(p->foo_, 5); // the FooItf ctor just stores 2+3 in foo_.
// Use a couple of different ways of declaring what should result in the
// same type as `p` is of.
scoped_refptr<Ref<FooItf>::Type> p2 = p;
Ref<FooItf>::Ptr p3 = p;
}
{
// Same for `Foo`
auto p = make_ref_counted<Foo>(2, 3);
EXPECT_NE(p.get(), nullptr);
EXPECT_EQ(p->foo_, 5);
scoped_refptr<Ref<Foo>::Type> p2 = p;
Ref<Foo>::Ptr p3 = p;
}
}
} // namespace rtc