i’m wondering when an instance of a TInterfacedObject derived class is destroyed and who calls the destructor. I wrote a ScopedLock class, which should automatically call the Release
method of a synchronization object when the instance goes out of scope. It’s an RAII concept known from C++, but i don’t know if it is guaranteed that the destructor is called, when the lock instance goes out of scope.
ILock = interface
end;
ScopedLock<T: TSynchroObject> = class(TInterfacedObject, ILock)
strict private
sync_ : T;
public
constructor Create(synchro : T); reintroduce;
destructor Destroy;override;
end;
implementation
{ ScopedLock<T> }
constructor ScopedLock<T>.Create(synchro: T);
begin
inherited Create;;
sync_ := synchro;
sync_.Acquire;
end;
destructor ScopedLock<T>.Destroy;
begin
sync_.Release;
inherited;
end;
{ Example }
function Example.Foo: Integer;
var
lock : ILock;
begin
lock := ScopedLock<TCriticalSection>.Create(mySync);
// ...
end; // mySync released ?
It works fine in a simple test case, but is it safe?
Yes, that is save. Your code
is compiled as the following pseudocode
You can see that when lock var goes out of scope its ref count is decremented, became zero and lock object is automatically destroyed.