Check if the pointer is nil before you create an instance of TTest class, like this:
var
Test: TTest;
begin
if APar <> nil then
begin
Test := TTest.Create(APar);
//...
end
else
DoSomethingElse;
end;
but that assumes that the OP has control over the code that creates the object what happens if he is responsible for the class but not how its used?
That is exactly the case, hence it is unfortunately no option to check the condition outside the constructor.
@eljo: I read about having an exception raised to stop the instance from being created (and memory cleaned up) in my research before. Maybe it is just me, but this feels like a dirty trick and an abuse of the exception mechanism.
Is there a "clean way" of interrupting the instance creation?
REMARK: While writing this, this came in:
You can call Fail inside a constructor.
The constructor will return Nil in that case.
constructor TMyClass.Create;
begin
if SomeCriticalConditionIsNotMet then
Fail;
...
//rest of constructor code
end;
...
var
C: TMyClass;
begin
C := nil;
C := TMyClass.Create;
if C = nil then ErrorMessageAndHaltApplication;
//Do something with C
C.Free;
end..
There wil be no memory leak (for the instance of C, that is).
Bart
That's what I was looking for! Thanks Bart and everybody!