In the above example the two expressions were SameQ but not SameInstanceQ. In the following example expr1 and expr2 both point to the same expression instance:
In[6]:=
CleanupAfter
[expr1=Range[20],Print["expr1deleted"]]
CleanupAfter
[expr2=expr1,Print["expr2deleted"]]
SameInstanceQ
[expr1,expr2]
Out[6]=
True
Both of the added cleanup functions will be called when all references to the data are gone:
In[7]:=
expr1=.
In[8]:=
expr2=.
expr1deleted
expr2deleted
Set the history length to the default value and evaluate the same code as above:
In[1]:=
$HistoryLength=∞;g=RandomGraph[{4,5}]
Out[1]=
In[2]:=
CleanupAfter
[g,Print["ghasbeencleared"]]
Clearing the symbol g does not remove all references to the object:
In[3]:=
g=.
The value associated with g is still stored in the history: