Object lifetime management · Issue #609 · pybind/pybind11 (original) (raw)
I am trying to solve an ownership problem in pybind11.
I have to configure a hierarchy of objects in python.
In c++ this is done like:
InputVariable* _angle = new InputVariable;
_small = new Bell("small", -5.000, 5.000, 8.000);
_angle->addTerm(_small);
_big = new Bell("big", 5.000, 5.000, 8.000);
_angle->addTerm(_big);
The python equivalent:
_angle = InputVariable("angle", -5.0, 5.0)
_small = PF.Bell("small", -5.0, 5.0, 8.0, 1.0)
_angle.addTerm(_small)
_big = PF.Bell("big", 5.0, 5.0, 8.0, 1.0)
_angle.addTerm(_big)
In c++ the destructor of the Inputvariable delete's its Bell's.
Thus the InputVariable owns its Bells(and is responsible for cleaning them up).
When using python, this results in a conflict, because when creating the Bell's these are owned by the python interpreter, adding those with the addTerm function does not transfer this membership:
void InputVariable::addTerm(Term* term)
{
_terms.push_back(term);
}
During destruction (or memory collection in python) the d'tor of InputVariable is called which contains these statements:
InputVariable::~InputVariable()
{
for (std::size_t i = 0; i < _terms.size(); ++i) {
delete _terms.at(i);
}
}
The result is: kabang, since the Bell's are destructed twice.
What is the best approach to solve this, without changing the existing c++ code?
I hope this is the right platform to ask this question. If not could you please refer me to the place that is?