cpp-common/bt2: make `{OptionalBorrowedObject,SharedObject}::operator bool` explicit
authorSimon Marchi <simon.marchi@efficios.com>
Tue, 12 Mar 2024 20:17:50 +0000 (16:17 -0400)
committerSimon Marchi <simon.marchi@efficios.com>
Tue, 26 Mar 2024 18:56:36 +0000 (14:56 -0400)
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 <simon.marchi@efficios.com>
Reviewed-on: https://review.lttng.org/c/babeltrace/+/12043
Reviewed-by: Philippe Proulx <eeppeliteloop@gmail.com>
Tested-by: jenkins <jenkins@lttng.org>
src/cpp-common/bt2/optional-borrowed-object.hpp
src/cpp-common/bt2/shared-object.hpp

index 941a87b1e96f0525eb9cfd5db7064ff87e5d5c0e..a967c273a5242da88a412320c52be5bd0efb11f8 100644 (file)
@@ -174,7 +174,7 @@ public:
         return _mLibObjPtr;
     }
 
-    operator bool() const noexcept
+    explicit operator bool() const noexcept
     {
         return this->hasObject();
     }
index 124cff48b49086ce16ede66647eecfdfa01a694b..1f68906caceca1c4363af065e125d69bc3959ae0 100644 (file)
@@ -241,7 +241,7 @@ public:
         return _mObj.operator->();
     }
 
-    operator bool() const noexcept
+    explicit operator bool() const noexcept
     {
         return _mObj.hasObject();
     }
This page took 0.02705 seconds and 4 git commands to generate.