Commit 9f42d66a authored by Kenton Varda's avatar Kenton Varda

Add way to check if a refcounted object has other references.

parent 6d580639
......@@ -34,13 +34,18 @@ struct SetTrueInDestructor: public Refcounted {
TEST(Refcount, Basic) {
bool b = false;
Own<SetTrueInDestructor> ref1 = kj::refcounted<SetTrueInDestructor>(&b);
EXPECT_FALSE(ref1->isShared());
Own<SetTrueInDestructor> ref2 = kj::addRef(*ref1);
EXPECT_TRUE(ref1->isShared());
Own<SetTrueInDestructor> ref3 = kj::addRef(*ref2);
EXPECT_TRUE(ref1->isShared());
EXPECT_FALSE(b);
ref1 = Own<SetTrueInDestructor>();
EXPECT_TRUE(ref2->isShared());
EXPECT_FALSE(b);
ref3 = Own<SetTrueInDestructor>();
EXPECT_FALSE(ref2->isShared());
EXPECT_FALSE(b);
ref2 = Own<SetTrueInDestructor>();
EXPECT_TRUE(b);
......
......@@ -59,6 +59,10 @@ class Refcounted: private Disposer {
public:
virtual ~Refcounted() noexcept(false);
inline bool isShared() const { return refcount > 1; }
// Check if there are multiple references to this object. This is sometimes useful for deciding
// whether it's safe to modify the object vs. make a copy.
private:
mutable uint refcount = 0;
// "mutable" because disposeImpl() is const. Bleh.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment