# Smart pointer for Mathematica?

Would the implementation of the smart pointer idea be possible in Mathematica ?

Let's say I have an object "o" of the form Class[object] where object is an Association, and Class has the HoldFirst attribute.

It should be easy to add to a reference count, counting the number of times "o" is stored in other variables.

But how could we decrement this reference count automatically, if it's even possible ? The goal of the reference count would be to delete object when the reference count reaches 0.

Are certain functions called under the hood by Mathematica, when deleting a list for example, and we could capture this call with an UpValues definition on Class in order to decrement the reference count ?

Or is all the memory management done at C level and we don't have to access it ?

• Why would you want to do that? – user21 Feb 6 '15 at 9:06
• This is the entire purpose of the Temporary attribute. – Oleksandr R. Feb 6 '15 at 10:31
• For what it is worth, the C level (which works at all altitudes, not just sea level) memory management does use a reference counting scheme. And as suggested by @OleksandrR., use of the Temporary attribute can be helpful especially in cases where a reference might otherwise be orphaned (I think this can happen with DownValues local to Module though I do not recall the issues in any detail). – Daniel Lichtblau Feb 6 '15 at 16:57
• @DanielLichtblau One case of orphaned references I described here, and in fact, it being Temporary doesn't prevent it, in that case. What's essential in that scenario is that the symbol is referenced by some other one, external to its scope, and that indeed, it has one of DownValues, UpValues or SubValues defined. In this scenario, it does not matter whether the referencing symbol is later removed or not. – Leonid Shifrin Feb 6 '15 at 18:25
• My goal would be to do Class[object].delete[] when the reference would be garbage collected. So even if Temporary were a solution, I would still need to know when the deletion of the temporary symbol happens. – faysou Feb 7 '15 at 14:59