Paul A. wrote:
> What follows is a snippet from an email sent to me by a friend who is
> a C++ programmer.
>
> ***
>> In C++, you create an object that sets a new process priority when
>> it's created and resets back the priority
>> when the object is destroyed.
>> And the object automatically gets destroyed when it goes out of
>> scope, i.e. when the functions were it's
>> created returns.
>> Regardless how may return paths there are, you never have to
>> remember to restore the process priority,
>> the destruction of the object takes care of that.
>>
>> I use this technique a lot, you might know about it - it's called
>> RAII (Resource Acquisition Is Initiallization)
> ***
>
> Sounds very useful. Do we have an analogous construct in Delphi?
Sort of. It's not automatic. The thing that makes it possible in C++ is
that classes are value types. They live on the stack, and when they go
out of scope, their destructors get called automatically. Another
contributing factor is that in C++, a function can have many scopes.
Every new set of braces defines a new scope, so in the example above,
you could force the process-priority object to be destroyed halfway
through the function by limiting its scope accordingly.
In Delphi, we usually use try-finally blocks to ensure that things get
cleaned up as a function is returning. Whereas in C++ we could write this:
{
ProcessPriority pp(3);
// etc.
}
In Delphi we'd write this:
var
pp: TProcessPriority;
begin
pp := TProcessPriority.Create(3);
try
// etc.
finally
pp.Free;
end;
Using interfaces, we can make our code a little less wordy. We could
write the above like this:
var
pp: IProcessPriority;
begin
pp := TProcessPriority.Create(3);
// etc.
end;
The interface variable will get set to nil as it leaves scope, and that
should cause the underlying object to get freed.
One thing I associate with RAII is that an object gets initialized
during construction and only during construction.
--
Rob