Sundial Servic
Delphi Developer |
Wed, 18 Jun 1902 08:00:00 GMT
Re:(no subject)
QuoteIn article <4cj28q$...@ankka.csc.fi> <pla...@siba.fi> writes: >OBJECT COPYING? >I have encountered the following problem: >When copying a object (a instance of certain class) by assignin B := A;, >the Turbo Pascal actually assigns the pointer of A to the B. This means >that every change made to data fields of A after that is reflected in B. >How it is possible to copy a instance of object? I mean, just copy the >values of data fields of given object just like records? It is of course >possible to do it by hand, copying each field at a time, but that is not >very clever.
When you assign two pointers (and in TP, a class is a pointer), you are indeed copying the four-byte pointer value from one location to the other so that, now, the two variables point to the same spot in memory and the chunk of storage pointed to by the former pointer is now "LOSSSTTT!!! IN SPAAAACCEE!" If you want to copy the values, one way to do it is to use a MemCopy-type routine, something like: "MemCopy(a^, b^, sizeof(a^))" -- and watch out for those "^"s lest you copy over the *pointer* (and all the memory nearby!) instead of what the pointer is pointing *to!* The Delphi implementation works slightly differently with its notion of an "Assign()" method. This is actually better because it is something that each descendent class can override if it chooses. Whereas many classes might be such that a simple memcopy, performed by "someone else," would work fine, other types of objects, like Bitmaps, would not work so well. The idea is that it should be the class's responsibility, not that of a class client, to "know" how to correctly copy an instance of a class. In some cases, the best way to copy the class *is* to do it variable-by-variable, as inelegant as that may appear to be. It's all the same to the computer. But I recommend defining a class-method, as with "Assign," in order to do it. /mr/
|