2

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I am going to use the object a but I wont free it. When I free c do I have to free FCheck as well or not? a is public and created on form create, c is created in a procedure
@RaffaeleRossi Usually, objects should only get free'd by the same class which created it. You shouldn't ever have to worry about freeing it anywhere else, unless you have the possibility of transferring ownership to something else. "Ownership" in this sense means just the responsible class.
Aaah ok got it. So what I am doing is fine, because FCheck will die anyway when I will call c.Free . Correct? Gonna accept

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.