digitalmars.D.learn - class destructors and sub-objects
- d coder (24/24) Aug 29 2013 Greetings
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (9/28) Aug 29 2013 from the
Greetings I have a question on class destructor method. D documentation for destructors says: "The garbage col=ADlec=ADtor is not guar=ADan=ADteed to run the de=ADstruc= =ADtor for all un=ADref=ADer=ADenced ob=ADjects. Fur=ADther=ADmore, the order in which= the garbage col=ADlec=ADtor calls de=ADstruc=ADtors for un=ADref=ADer=ADence ob=ADjects= is not spec=ADi=ADfied. This means that when the garbage col=ADlec=ADtor calls a de=ADstruc=ADtor for an ob=ADject of a class that has mem=ADbers that are ref=ADer=ADences to garbage col=ADlected ob=ADjects, those ref=ADer=ADences= may no longer be valid. This means that de=ADstruc=ADtors can=ADnot ref=ADer=ADenc= e sub ob=ADjects." Now I have a class A and it refers to subobject B. But B may or may not have other objects referring to it. As a result, an object of A is GCed, but subobject B may or may not be getting garbage collected. In this scenario, am I allowed to make a reference to subobject B from the destructor of A? Is there a way to find out if B is garbage collected or not? Regards - Puneet
Aug 29 2013
On 08/29/2013 06:58 AM, d coder wrote:> GreetingsI have a question on class destructor method. D documentation for destructors says: "The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which thegarbagecollector calls destructors for unreference objects is not specified. This means that when the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references may no longer be valid. This means that destructors cannot reference sub objects." Now I have a class A and it refers to subobject B. But B may or may not have other objects referring to it. As a result, an object of A is GCed, but subobject B may or may not be getting garbage collected. In this scenario, am I allowed to make a reference to subobject Bfrom thedestructor of A?The way I read it, it is exactly what the documentation warns against. No, A's destructor cannot reference B member.Is there a way to find out if B is garbage collected or not?Not on B member itself because it is no more. :) It is conceivable to maintain a bitmap to determine whether an object is still alive. The object's destructor can flip its bit to 0.Regards - PuneetAli
Aug 29 2013