Raffaele Rossi
Raffaele Rossi

Reputation: 3137

Delphi object reference in constructor

Let's say that I have this kind of code in my unit:

TClass = class(tobject)
 // ... implementation ...
end;

TControl = class(tobject)
 private
  FCheck: TClass
 public
  constructor Create(value: TClass);
  // ... implementation...
end;

constructor TControl.Create(value: TClass);
begin 
 FCheck := value;
end;

As you can see the control class is going to take a TClass as parameter in the constructor, so I need to do something like this:

//The 'a' is a TClass that has already been created

c := TControl.Create(a);
try
 //... do what I need ...
finally
 c.Free;
end;

This is very basic: I am going to use a as parameter of the constructor but I cannot understand if what I am doing is safe. Do I have a memory leak?

In the constructor I do FCheck := value and I guess that it's correct because I am passing a reference to the object. Do I have to implement a destructor in TControl to free the FCheck? I cannot understand if I am managing correctly the FCheck object.

Upvotes: 2

Views: 391

Answers (1)

Jerry Dodge
Jerry Dodge

Reputation: 27296

No, you do not need to destroy this object from within the class, assuming it already has an owner from elsewhere. It is however 100% up to you what actually owns it, but it should only have one owner. Meaning, a class which is responsible for the lifetime of that instance. It all depends on your specific requirements. It could be owned in one place initially, and then at some point you can pass the ownership to something else. In your case, it is possible to pass it into this constructor, and then consider that the owner. If this is the case, then yes, you do need to destroy it from within the class. But again, it should only have one owner at any given time.

Upvotes: 3

Related Questions