www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - D newbie question - Automating resource allocation and deallocation

reply "Tony" <talktotony email.com> writes:
Hi all,

I'm grappling with the concept of how to automatically allocate and
deallocate resources in D (in a deterministic way) and I'd be grateful for
any help.

For example, in C++ this process can be automated by the creation of a class
where the constructor allocates and the destructor deallocates.

In Lisp, the same process can be automated through the use of macros.

In D, am I right in assuming that we use the class allocator and deallocator
for this purpose? And that if the class is defined as auto the process is
deterministic (defined by the lexical scope in which the allocator is
called?)

Also, does D support any other techniques for automating resource
allocation/deallocation?

Thanks.

Tony

Melbourne Australia
Mar 04 2005
parent "Ben Hinkle" <bhinkle mathworks.com> writes:
"Tony" <talktotony email.com> wrote in message 
news:d09s9f$19c5$1 digitaldaemon.com...
 Hi all,

 I'm grappling with the concept of how to automatically allocate and
 deallocate resources in D (in a deterministic way) and I'd be grateful for
 any help.

 For example, in C++ this process can be automated by the creation of a 
 class
 where the constructor allocates and the destructor deallocates.

 In Lisp, the same process can be automated through the use of macros.

 In D, am I right in assuming that we use the class allocator and 
 deallocator
 for this purpose?
Class allocators and deallocators are for the actual memory used by the class instance - not for any resources the ctor (constructor) will need. If I understand your question you should be using ctors and dtors. If the "resource" you want to manage is memory then usually the GC manages that. If you don't want to use the GC you can either use malloc and free directly or use class allocators and deallocators. It would help to know more about what you are trying to do.
 And that if the class is defined as auto the process is
 deterministic (defined by the lexical scope in which the allocator is
 called?)
Allocate in the ctor. Deallocate in the dtor. To explicitly deallocate call "delete". To delete at the end of the scope make the variable auto. It is very important, though, to not rely on any other GC-managed resource in the dtor since the order in which the dtors are called is random (hence you never know if any other reference is valid).
 Also, does D support any other techniques for automating resource
 allocation/deallocation?
Not that I can think of. "exit" will typically automatically clean up any external resources but that probably isn't what you mean :-)
 Thanks.

 Tony

 Melbourne Australia
Mar 04 2005