Reputation: 2520
In my framework I have a DataSource1 instance that was dropped in design time on a Form.
At some point at run time I need to "convert" it to a reference to another DataSource2 (on a Data Module).
Is simply setting:
DataSource1 := DataSource2;
Enough to make DataSource1 a reference of DataSource2? it appears that DataSource1 is not being destroyed at this point - It is destroyed when the Owner of DataSource2 is destroyed, And that there are in fact two instances of TDataSource.
Or do I need to explicitly free DataSource1 first?
DataSource1.Free;
DataSource1 := DataSource2;
What is the correct way? (Besides declaring DataSource1 as a reference in the first place)
Upvotes: 2
Views: 230
Reputation: 612834
When you declare a variable to be of a type that inherits from TObject, you are actually declaring a pointer.
When you call a constructor, you are creating an instance. The constructor returns a pointer to that instance. You typically assign that pointer to a variable like this:
Obj1 := TMyClass.Create;
You can make a second variable point to, or refer to, the instance with simple assignment:
Obj2 := Obj1;
The object is destroyed by calling Free:
Obj1.Free;
At this point Obj2 refers to an object that no longer exists. We say that Obj2 is a stale reference.
In your case you need to free the first object:
Upvotes: 4