General Handle Removal

16 ビュー (過去 30 日間)
Sean
Sean 2012 年 5 月 16 日
I am looking for a better way to close out/clean up handle references.
Specifically: 1) 'Clear' removes the variable holding the handle ref, but doesn't clean it up. 2) 'Delete' cleans up the reference, but doesn't clear the variable. 3) If I delete an invalid handle, I get ugly warnings
Therefore I have been doing the following:
if isvalid(handlex)
delete(handlex)
end
clear handlex
It seems like there must be a better way to do this (or even a single command). Can anyone provide insight on a better way to do this (especially in larger programs with many independent handles) or help me understand why matlab doesn't have a better way?
thanks, Sean

採用された回答

Walter Roberson
Walter Roberson 2012 年 5 月 16 日
You are correct about the sequence.
Handles are not objects: they are references to objects. Many different references can exist to the same object.
Suppose you are in a meeting, and while you are listening, you doodle "I want my lunch" on a piece of paper. That piece of paper now has a reference to your lunch. If you throw out the piece of paper, you do not want your lunch to be automatically thrown out as well!
If there was a combined operation, you can be sure that many people would not understand and would misuse it, much like the many many postings we see that use "clear all" without understanding just how much "all" includes.
  1 件のコメント
Sean
Sean 2012 年 5 月 16 日
I think I understand what you are saying... Let me outline a scenario to see if I understand your argument correctly.
If I was writing code that communicated over a serial port, I would get a reference to the port. Then, if I wasn't strict about encapsulating different parts of my code, I might pass the reference around to various other functions, modules, objects, etc. If I wasn't careful, I could end up 'clear/deleting' the reference in one area of the code and then cause errors everywhere else that the reference to the port was still being used. By declining to provide a single operation, you make the code potentially a bit messier, but you force the programmer to intentionally delete as opposed to casually 'clear/deleting' everywhere and potentially getting confused.
Does that sum it up correctly?
Given that as an unfortunate but reasonable purpose for not combining the two functions, is there a command or flag that can be used to say "delete this handle if its still valid, but don't bother me with warnings or errors if it isn't" (or do I just need to include checks everytime I delete a handle?
Thanks.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by