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)
commit53756eaca16229acb05969a1d7278c59fc4d9d72
treeb89fe15e764a5c716dc42672c512975fcec72cc1
parent8de58945ad42801d8a4906f692a5e72e8f967f46
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 <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
This page took 0.024761 seconds and 4 git commands to generate.