Skip to content

Commit

Permalink
Add a boolean conversion to intrusive_ptr. (#535)
Browse files Browse the repository at this point in the history
This change adds a boolean conversion to `intrusive_ptr`. While type
conversions are frowned upon by the Google style guide, boolean
conversions of this form are highly idiomatic for C++ smart pointers,
and are defined on both `std::unique_ptr` and `std::shared_ptr`. This
method allows more syntactically-fluid use of the `GetIf` function on
`Attribute`, as with it we can write code like so:

```
if (intrusive_ptr<Int64Attribute> int64_attr =
  attr.GetIf<Int64Attribute>()) {
...
}
```

with the conversion to `bool` allowing for the testing of the introduced
`int64_attr` local.

Closes #535

COPYBARA_INTEGRATE_REVIEW=#535 from google-research:intrusive_ptr_convert_to_bool@winterrowd d9d75ce
PiperOrigin-RevId: 443711224
  • Loading branch information
markww authored and arcs-c3po committed Apr 22, 2022
1 parent 67d8731 commit 1dcfcde
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/common/utils/intrusive_ptr.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ class intrusive_ptr {

T* operator->() const { return ptr_; }
T* get() const { return ptr_; }
explicit operator bool() const {
return ptr_ != nullptr;
}

private:
void Swap(intrusive_ptr<T>& other) {
Expand Down
8 changes: 8 additions & 0 deletions src/common/utils/intrusive_ptr_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -238,5 +238,13 @@ TEST(IntrusivePtrTest, ComparisionAgainstNullPtrs) {
EXPECT_EQ(null, nullptr);
EXPECT_EQ(nullptr, null);
}

TEST(IntrusivePtrBoolConversionTest, IntrusivePtrBoolConversionTest) {
RefCountedTypePtr ptr = make_intrusive_ptr<RefCountedType>();
EXPECT_TRUE(ptr);
RefCountedTypePtr null;
EXPECT_FALSE(null);
}

} // namespace
} // namespace raksha

0 comments on commit 1dcfcde

Please sign in to comment.