Board index » delphi » Rookie constructor question

Rookie constructor question

Sorry,
but rookies come with rookie questions:

Instance := TMyObject.Create

what is the state of Instance when Create fails - nil ?
And how can force Instance to be nil from within my constructor if some of
my own actions fail(i.e. opening a device etc..)
TIA, Uwe

 

Re:Rookie constructor question


Uwe <planco...@aol.com> wrote in article
<19970204135900.IAA04...@ladder01.news.aol.com>...

Quote
> Sorry,
> but rookies come with rookie questions:

yeah, and everybody's a rookie at something...

Quote
> Instance := TMyObject.Create

> what is the state of Instance when Create fails - nil ?
> And how can force Instance to be nil from within my constructor if some
of
> my own actions fail(i.e. opening a device etc..)

You could define Instance to be nil ere creating it,
in the initialization section of a unit, lke this
initializaiton
  Instance := nil;
but then the value is never used unless you are testing
for the existence of a Singleton, like this...

proc MakeObject;
 if Instance <> nil then begin
   Instance := TMyObject.Create;
 end;
end;

Another thing to consider is throwing an exception from
inside your Create, after you Free memory that has been
allocated already. Catching the exception with an 'except'
or 'finally' alters the viewpoint of what 'Instance' should contain.

ctor TMyobject.Create;
begin
  inherited Create; // throws an exception?
  dm := TDataMember.Create; // throws also?
  try
    // attempt to allocate resource
  except
    on EAllocateResourceFails do  dm.Free;
  end;
end;

Quote
> TIA, Uwe

--
Grace + Peace   *   Peter N Roth  *   Engineering Objects International
Tools for Developers: ClassBuilder 4 for Delphi, ClassBuilder++ for C++
Visit our website at http://www.inconresearch.com/eoi

Other Threads