TDPL: Manual invocation of destructor
Max Samukha
spambox at d-coding.com
Tue Aug 10 07:24:06 PDT 2010
On 08/09/2010 10:41 PM, Andrei Alexandrescu wrote:
>
> I thought we did!
>
Ok, C# way is complicated, awkward etc. but it still allows me to
reasonably compose objects that hold deterministically manageable
resources. Imagine an object that owns another object that owns a resource:
class Resource
{
private int handle;
this() { handle = acquireResource(); }
~this { releaseResource(handle); }
}
class ResourceOwner
{
private Resource resource;
this() { resource = new Resource; }
}
In C# I would do something like this (using D syntax and conventions):
class Resource : IDisposable
{
private int handle;
this() { handle = acquireResource(); }
void dispose()
{
if (handle)
{
releaseResource(handle);
handle = 0;
}
}
~this { dispose(); }
}
class ResourceOwner : IDisposable
{
private Resource resource;
this() { resource = new Resource; }
void dispose()
{
resource.dispose();
}
}
The above enables me to:
1. Not care about releasing the resource (some consider this a
disadvantage):
auto owner = new ResourceOwner;
The resource and memory will be eventually freed by the GC.
2. Free the resource deterministically:
auto owner = new ResourceOwner;
owner.dispose();
3. RAII:
using (auto owner = new ResourceOwner)
{
...
}
The resource will be freed at the end of the "using" block.
Is it possible to realize 2-3 in D using clear()/scoped()?
More information about the Digitalmars-d
mailing list