ChimeraTK-ApplicationCore 04.06.00
Loading...
Searching...
No Matches
PyOwnershipManagement.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Deutsches Elektronen-Synchrotron DESY, MSK, ChimeraTK Project <chimeratk-support@desy.de>
2// SPDX-License-Identifier: LGPL-3.0-or-later
3#pragma once
4
5#include <list>
6#include <memory>
7
8namespace ChimeraTK {
9
10 /********************************************************************************************************************/
11
14 public:
15 virtual ~PyOwnedObject() = default;
16 };
17
18 /********************************************************************************************************************/
19
23 public:
27 template<class Child, typename... Args>
28 Child* make_child(Args... args) {
29 auto ptr = std::make_unique<Child>(args...);
30 Child* rv = ptr.get();
31
32 _children.emplace_back(std::move(ptr));
33 return rv;
34 }
35
36 private:
37 // Note about ownership and deinit problem.
38 // When naively mapping VariableGroup to Python, we run into a problem at the deinitialization phase:
39 // The accessors held by the VariableGroup reference back to their owner (the VariableGroup) and
40 // in their C++ destructor, they actually call functions of the owner.
41 // On the other hand, if a container in Python is destroyed, Python first releases the container
42 // and then the elements. This is different from a C++ class holding the elements as class members.
43 // To solve the issue, we decided to take away ownership handling from Python and explicitly take
44 // care on the C++ side. This requires some ownership lists (below) and handing out accessors
45 // in pybind11 with return_value_policy::reference.
46 // Note also, when mapping VariableGroup as PyVariableGroup, and user code subclasses PyVariableGroup,
47 // attributes of PyVariableGroup automatically get destroyed before ~PyVariableGroup executes.
48 // But this is not enough to cover case of non-subclassed PyVariabledGroup with dynamic attributes!
49 // So we still need the general solution described above.
50 std::list<std::unique_ptr<PyOwnedObject>> _children;
51 };
52
53 /********************************************************************************************************************/
54} // namespace ChimeraTK
Base class used for all objects in the Python world which can be owned by another object.
virtual ~PyOwnedObject()=default
Base class used for all objects in the Python world which can own other objects and can be owned them...
Child * make_child(Args... args)
Create object of type Child by passing the given arguments to the constructor of Child,...
InvalidityTracer application module.