pybind11
pybind11 copied to clipboard
[BUG]: Failed C++ Assert is Ignored in Python
Required prerequisites
- [X] Make sure you've read the documentation. Your issue may be addressed there.
- [X] Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
- [X] Consider asking first in the Gitter chat room or in a Discussion.
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