From 53756eaca16229acb05969a1d7278c59fc4d9d72 Mon Sep 17 00:00:00 2001 From: Simon Marchi Date: Tue, 12 Mar 2024 16:17:50 -0400 Subject: [PATCH] cpp-common/bt2: make `{OptionalBorrowedObject,SharedObject}::operator bool` explicit This code doesn't really make sense (what I really wanted to do was to compare the underlying lib pointers), but I made this mistake on more than one occasion: if (someOptionalBorrowedObject == someSharedObject) What happens is: since `operator bool` for both types is implicit, they get implicitly converted to bool. As a result, the condition checks if both objects contain an object or don't contain an object. I consider this a pitfall, as it compiles but it is likely never what we'll want to do. Make `operator bool` for both types explicit to avoid that. This is what is done in the STL for `shared_ptr` [1] and `optional` [2]. Note that even if `operator bool` is explicit, it remains implicitly convertible to bool in certain contexts [3], such as an if condition. [1] https://en.cppreference.com/w/cpp/memory/shared_ptr/operator_bool [2] https://en.cppreference.com/w/cpp/utility/optional/operator_bool [3] https://stackoverflow.com/questions/39995573/when-can-i-use-explicit-operator-bool-without-a-cast Change-Id: I2b2377323ca620162442cb7f0305763c034d13d8 Signed-off-by: Simon Marchi Reviewed-on: https://review.lttng.org/c/babeltrace/+/12043 Reviewed-by: Philippe Proulx Tested-by: jenkins --- src/cpp-common/bt2/optional-borrowed-object.hpp | 2 +- src/cpp-common/bt2/shared-object.hpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cpp-common/bt2/optional-borrowed-object.hpp b/src/cpp-common/bt2/optional-borrowed-object.hpp index 941a87b1..a967c273 100644 --- a/src/cpp-common/bt2/optional-borrowed-object.hpp +++ b/src/cpp-common/bt2/optional-borrowed-object.hpp @@ -174,7 +174,7 @@ public: return _mLibObjPtr; } - operator bool() const noexcept + explicit operator bool() const noexcept { return this->hasObject(); } diff --git a/src/cpp-common/bt2/shared-object.hpp b/src/cpp-common/bt2/shared-object.hpp index 124cff48..1f68906c 100644 --- a/src/cpp-common/bt2/shared-object.hpp +++ b/src/cpp-common/bt2/shared-object.hpp @@ -241,7 +241,7 @@ public: return _mObj.operator->(); } - operator bool() const noexcept + explicit operator bool() const noexcept { return _mObj.hasObject(); } -- 2.34.1