Skip to content

Commit c889ebd

Browse files
committed
Make operator bool() explicit
This prevents unwanted conversions to bool or int such as: ``` py::object my_object; std::cout << my_object << std::endl; // compiles and prints 0 or 1 int n = my_object; // compiles and is nonsense ``` With `explicit operator bool()` the above cases become compiler errors.
1 parent 135fd14 commit c889ebd

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

include/pybind11/pytypes.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ class handle : public detail::object_api<handle> {
8888
const handle& dec_ref() const { Py_XDECREF(m_ptr); return *this; }
8989

9090
template <typename T> T cast() const;
91-
operator bool() const { return m_ptr != nullptr; }
91+
explicit operator bool() const { return m_ptr != nullptr; }
9292
bool operator==(const handle &h) const { return m_ptr == h.m_ptr; }
9393
bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; }
9494
bool check() const { return m_ptr != nullptr; }
@@ -572,7 +572,7 @@ class none : public object {
572572
class bool_ : public object {
573573
public:
574574
PYBIND11_OBJECT_DEFAULT(bool_, object, PyBool_Check)
575-
// Allow implicit conversion from `bool`:
575+
// Allow implicit conversion from and to `bool`:
576576
bool_(bool value) : object(value ? Py_True : Py_False, true) { }
577577
operator bool() const { return m_ptr && PyLong_AsLong(m_ptr) != 0; }
578578
};

0 commit comments

Comments
 (0)