-
Notifications
You must be signed in to change notification settings - Fork 50
Weak References
The C++ backend by default creates objects using std::shared_ptr
, a reference counted shared pointer.
http://en.cppreference.com/w/cpp/memory/shared_ptr
Cyclic data structures will not work using only reference counted shared pointers. To break the cycle a weak pointer must be used, the child holds a weak pointer to its parent. The child then promotes the weak pointer to a reference counted pointer when it needs to use it, first checking if the pointer to the parent is still valid.
Rusthon will automatically detect when you need to use a weak pointer in an object, the only part you need to manage is promotion of the weak pointer by assigning it to a variable and testing if it is None
(nullptr). This works because std::weak_ptr
returns nullptr
if the reference has been deleted. When using custom weakref types this syntax to check if a weak pointer is still alive may not work, you can instead use weak.valid(ptr)
to check a weak reference, this style works with normal c++11 types and custom types. For more info on custom types, see: https://github.com/rusthon/Rusthon/wiki/Custom-Type-Templates
class Child:
def __init__(self, p:Parent):
self.parent = p
def foo(self):
parent = self.parent
#if parent is None: ## this style only works standard c++11 smart pointers
if weak.valid(parent): ## this works with custom types and standard c++11 smart pointers.
print('do clean up...')
else:
do something with parent
You can also be more explicit by using weak.unwrap
parent = weak.unwrap(self.parent)
In order for Rusthon to automatically detect the reference cycle, the child must be stored in a list in the parent.
class Parent:
def __init__(self, children:[]Child):
self.children = children