Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

duplicate an instance of an object

Status
Not open for further replies.

DaZZleD

Programmer
Joined
Oct 21, 2003
Messages
886
Location
US
In my project I use self created classes. I instantiate an object then when I create another one that equals the first, delphi actually creates the second as a pointer to the first. I would like to actually duplicate the object in memory, as a new instance... Is there any method for it, or do I have to create my own duplicate method that copies each of the attributes' values of the first object to the second?
 
hi

I think the api call CopyMemory would do it. Also Delphi's Move procedure is worth a go. Delphi's example (I'm sure this should work with objects):-

var
A: array[1..4] of Char;
B: Integer;
begin
Move(A, B, SizeOf(B)); { SizeOf = safety! }
end;

lou

 
Danny Thorpe's highly regarded book "Delphi Component Design" covers this on pages 205 - 210.

If your class descends from TPersistent then Assign support is provided.

The book gives an example of a simple implementation of Assign. I hope I'm not infringing copyright by reproducing it here.
Code:
procedure TStrings.Assign(Source: TPersistent);
begin
  if Source is TStrings then
  begin
    BeginUpdate;
    try
      Clear;
      AddStrings(TStrings(Source));
    finally
      EndUpdate;
    end;
  end else inherited Assign(Source);
end;

HTH

Andrew
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top