How do I track the number of instances of a given handle?

12 visualizaciones (últimos 30 días)
John Scanlon
John Scanlon el 17 de Oct. de 2019
Respondida: Guillaume el 17 de Oct. de 2019
I'm wondering if there is a way to track the number of instances of a handle. Example:
% Create an instance of the handle here:
handleObj = handleClass;
% Add a reference to it here:
handleObj2 = handleObj;
I want some kind of property stored in the handle that would now tell me there are 2 instances of it in existence, and each time I delete one it will decrement. Is this possible?
  2 comentarios
John Scanlon
John Scanlon el 17 de Oct. de 2019
Thanks Walter! I had a look at these two links.
With regard to the first link, it would have been nice if I could just inherit the meta.class implementation that Guillaume recommended, and I gave it a shot, but inheriting that class appears to put a lot of constraints on what I can do with my existing code in terms of overloads. Incrementing and decrementing object count based on InstanceCreated and InstanceDestroyed is essentially what I want to do though, although it would be nice if ML just had some access to a more absolute handle property for this.
For the second link, I'm not completely clear on how to integrate mex with my existing class, but I'll look into it a bit more.

Iniciar sesión para comentar.

Respuestas (1)

Guillaume
Guillaume el 17 de Oct. de 2019
I'm curious what you mean by "inheriting that class appears to put a lot of constraints on what I can do with my existing code in terms of overloads."?
However, note that your question doesn't match your example code. With this code:
% Create an instance of the handle here:
handleObj = handleClass;
% Add a reference to it here:
handleObj2 = handleObj;
there is still only one instance of the handle class. The two variables share the same instance.
If that is what you want to do, count the number of variables pointing to the same instance, then I'm afraid there's no way to do that. There's no mechanism at all in matlab to get information when the ref. count of variable gets incremented/decremented.
On the other hand, if what you want to do is indeed count the number of instances:
handleObj = handleClass; %one instance created
handleObj2 = handleObk; %still only one instance
handleObj3 = handleClass; %New instance, so now 2 instances
delete(handlObj); %Now just one instance, both handleObj and handleObj2 are now invalid handles
then the InstanceCreated and instanceDestroyed events of the meta class would do the job.

Etiquetas

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by