www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Garbage-collected structs vs garbage-collected classes

reply Sean Eskapp <eatingstaples gmail.com> writes:
When I was using a class to wrap SDL functions and structs, I would have a
problem that Derelict would unload before the garbage-collector cleaned up my
classes, resulting in errors when these classes destructed and tried to call
SDL functions in the process. However, the exact same code using structs to
wrap instead of classes does not produce these errors. For example, rather
than using
scope screen = new Screen(800, 600)
where Screen is a scope class, I'm using
auto screen = new Screen(800, 600)
where Screen is a struct. This also provides me the advantage of being able to
use delegates which use screen. Is there a reason for this?
Jan 22 2011
parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Saturday 22 January 2011 17:27:18 Sean Eskapp wrote:
 When I was using a class to wrap SDL functions and structs, I would have a
 problem that Derelict would unload before the garbage-collector cleaned up
 my classes, resulting in errors when these classes destructed and tried to
 call SDL functions in the process. However, the exact same code using
 structs to wrap instead of classes does not produce these errors. For
 example, rather than using
 scope screen = new Screen(800, 600)
 where Screen is a scope class, I'm using
 auto screen = new Screen(800, 600)
 where Screen is a struct. This also provides me the advantage of being able
 to use delegates which use screen. Is there a reason for this?

Well, IIRC struct destructors don't currently ever get called for any structs on the heap. So, there's no way that you'd get a problem when such a destructor runs, because it never runs. There are several bugs relating to struct destructors, and I'm not 100% sure what the current state of them is (I believe that they work properly for normal RAII), but in particular, for the moment, don't create a struct with new and expect its destructor to be run. http://d.puremagic.com/issues/show_bug.cgi?id=2834 - Jonathan M Davis
Jan 22 2011