pybind / pybind11

Seamless operability between C++11 and Python
https://pybind11.readthedocs.io/
Other
15.08k stars 2.05k forks source link

[BUG]: Failed C++ Assert is Ignored in Python #5106

Open xARTPOP opened 2 months ago

xARTPOP commented 2 months ago

Required prerequisites

What version (or hash if on master) of pybind11 are you using?

2.12.0

Problem description

In the C++ overloading of the operator[], I've got an assert to make sure the id being accessed isn't outside the bounds of my container. This works in the C++ code, but in Python, it gives no indication of the assert failure when accessing an invalid id and still returns a value, though I'm not sure where this value is coming from. Below is a reproduction of this behavior.

Reproducible example code

#include <pybind11/pybind11.h>
#include <pybind11/operators.h>

#include <array>
#include <assert>

class foo {
public:
        std::array<int, 4> data{1, 2, 3, 4};
        size_t size = 4;

        double operator[](const size_t idx) {
                assert(idx < this->size);
                return this->data[idx];
        }
};

namespace py = pybind11;

PYBIND11_MODULE(assert_issue, m) {
        py::class_<foo>(m, "foo")
                .def(py::init<>())
                .def("__getitem__", py::overload_cast<const size_t>(&foo::operator[]));
}

Is this a regression? Put the last known working version here if it is.

Not a regression