mirror of
https://github.com/pybind/pybind11.git
synced 2026-06-06 06:51:58 +00:00
Implement reference_internal with a keep_alive
reference_internal requires an `instance` field to track the returned reference's parent, but that's just a duplication of what keep_alive<0,1> does, so use a keep alive to do this to eliminate the duplication.
This commit is contained in:
@@ -161,10 +161,13 @@ void init_issues(py::module &m) {
|
||||
// Issue #328: first member in a class can't be used in operators
|
||||
#define TRACKERS(CLASS) CLASS() { std::cout << #CLASS "@" << this << " constructor\n"; } \
|
||||
~CLASS() { std::cout << #CLASS "@" << this << " destructor\n"; }
|
||||
struct NestA { int value = 3; NestA& operator+=(int i) { value += i; return *this; } TRACKERS(NestA) };
|
||||
struct NestABase { int value = -2; TRACKERS(NestABase) };
|
||||
struct NestA : NestABase { int value = 3; NestA& operator+=(int i) { value += i; return *this; } TRACKERS(NestA) };
|
||||
struct NestB { NestA a; int value = 4; NestB& operator-=(int i) { value -= i; return *this; } TRACKERS(NestB) };
|
||||
struct NestC { NestB b; int value = 5; NestC& operator*=(int i) { value *= i; return *this; } TRACKERS(NestC) };
|
||||
py::class_<NestA>(m2, "NestA").def(py::init<>()).def(py::self += int());
|
||||
py::class_<NestABase>(m2, "NestABase").def(py::init<>()).def_readwrite("value", &NestABase::value);
|
||||
py::class_<NestA>(m2, "NestA").def(py::init<>()).def(py::self += int())
|
||||
.def("as_base", [](NestA &a) -> NestABase& { return (NestABase&) a; }, py::return_value_policy::reference_internal);
|
||||
py::class_<NestB>(m2, "NestB").def(py::init<>()).def(py::self -= int()).def_readwrite("a", &NestB::a);
|
||||
py::class_<NestC>(m2, "NestC").def(py::init<>()).def(py::self *= int()).def_readwrite("b", &NestC::b);
|
||||
m2.def("print_NestA", [](const NestA &a) { std::cout << a.value << std::endl; });
|
||||
|
||||
Reference in New Issue
Block a user