From c889ebd0e151bce10f141461e9be588119eef546 Mon Sep 17 00:00:00 2001 From: Dean Moldovan Date: Mon, 17 Oct 2016 01:48:32 +0200 Subject: [PATCH] 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. --- include/pybind11/pytypes.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index 6ea7f7a5c..bfe169a72 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -88,7 +88,7 @@ public: const handle& dec_ref() const { Py_XDECREF(m_ptr); return *this; } template T cast() const; - operator bool() const { return m_ptr != nullptr; } + explicit operator bool() const { return m_ptr != nullptr; } bool operator==(const handle &h) const { return m_ptr == h.m_ptr; } bool operator!=(const handle &h) const { return m_ptr != h.m_ptr; } bool check() const { return m_ptr != nullptr; } @@ -572,7 +572,7 @@ public: class bool_ : public object { public: PYBIND11_OBJECT_DEFAULT(bool_, object, PyBool_Check) - // Allow implicit conversion from `bool`: + // Allow implicit conversion from and to `bool`: bool_(bool value) : object(value ? Py_True : Py_False, true) { } operator bool() const { return m_ptr && PyLong_AsLong(m_ptr) != 0; } };