[core] Add support for RefIfNonZero in InternallyRefCounted. (#34869)

The support already exists in RefCounted and DualRefcounted, so expose similar API for InternallyRefCounted class

Closes #34869

COPYBARA_INTEGRATE_REVIEW=https://github.com/grpc/grpc/pull/34869 from anicr7:orphanable_ref_if_nonzero f57c64dc62
PiperOrigin-RevId: 588514955
pull/35238/head
Anirudh Ramachandra 1 year ago committed by Copybara-Service
parent 626bf5351b
commit a58f3f2df5
  1. 11
      src/core/lib/gprpp/orphanable.h
  2. 26
      test/core/gprpp/orphanable_test.cc

@ -108,6 +108,17 @@ class InternallyRefCounted : public Orphanable {
}
}
GRPC_MUST_USE_RESULT RefCountedPtr<Child> RefIfNonZero() {
return RefCountedPtr<Child>(refs_.RefIfNonZero() ? static_cast<Child*>(this)
: nullptr);
}
GRPC_MUST_USE_RESULT RefCountedPtr<Child> RefIfNonZero(
const DebugLocation& location, const char* reason) {
return RefCountedPtr<Child>(refs_.RefIfNonZero(location, reason)
? static_cast<Child*>(this)
: nullptr);
}
private:
void IncrementRefCount() { refs_.Ref(); }
void IncrementRefCount(const DebugLocation& location, const char* reason) {

@ -103,6 +103,32 @@ TEST(OrphanablePtr, InternallyRefCountedWithTracing) {
baz->FinishWork();
}
class Qux : public InternallyRefCounted<Qux> {
public:
Qux() : Qux(0) {}
explicit Qux(int value) : InternallyRefCounted<Qux>("Qux"), value_(value) {}
~Qux() override { self_ref_ = RefIfNonZero(DEBUG_LOCATION, "extra_work"); }
void Orphan() override { Unref(); }
int value() const { return value_; }
void StartWork() { self_ref_ = RefIfNonZero(DEBUG_LOCATION, "work"); }
void FinishWork() {
// This is a little ugly, but it makes the logged ref and unref match up.
self_ref_.release();
Unref(DEBUG_LOCATION, "work");
}
private:
int value_;
RefCountedPtr<Qux> self_ref_;
};
TEST(OrphanablePtr, InternallyRefCountedIfNonZero) {
auto qux = MakeOrphanable<Qux>();
qux->StartWork();
qux->FinishWork();
}
} // namespace
} // namespace testing
} // namespace grpc_core

Loading…
Cancel
Save