pub trait Refcounted: Clone {
type WeakRef;
// Required methods
fn upgrade(this: &Self::WeakRef) -> Option<Self>
where Self: Sized;
fn downgrade(&self) -> Self::WeakRef;
}Expand description
A helper trait for refcounted objects. Reccounted items can more easily be lifted into closures without leaking data. This is accomplished by distinguising between “strong references” (cause the object to exist) and “weak referenes” (which do not prevent the object from being freed).
There is a refcounted!() macro to make declaring such types easier. A new strong reference can cheaply be created using the Clone trait.
Example usage:
let registry = core.registry();
// Generate a weak reference, so the closure does not force the object to be alive forever.
let registry_weak = registry.downgrade();
registry.add_listener(ProxyEvents {
// Use the some_closure!() macro to avoid this boilerplate
global: move |id, _perms, type_, version, props| {
let registry = registry_weak
.upgrade()
.expect("registry hook should not outlive registry");
let object = registry.bind(id, type_, version);
// ...
},
..Default::default()
});The closure! macro can be used to reduce the boilerplate of going through
the downgrade()/upgrade() cycle, especially for values that need to be sent into multiple
closures.
Required Associated Types§
Required Methods§
Sourcefn upgrade(this: &Self::WeakRef) -> Option<Self>where
Self: Sized,
fn upgrade(this: &Self::WeakRef) -> Option<Self>where
Self: Sized,
Try to convert a weak reference to a strong reference. If the underlying object isstill
alive, returns a Some continaing the value. If the underlying object’s strong reference
count dropped to zero, and was thus freed, this returns None.
Sourcefn downgrade(&self) -> Self::WeakRef
fn downgrade(&self) -> Self::WeakRef
Create a weak reference to the object. This reference does not impact the object’s lifecycle, and merely allows us the option to try to retrieve the object using Self::upgrade().
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.