Re: copying of objects [message #32455 is a reply to message #32452] |
Tue, 08 October 2002 05:40   |
David Fanning
Messages: 11724 Registered: August 2001
|
Senior Member |
|
|
Sebastian Loebbert (sebaaihb@peach.zrz.TU-Berlin.DE) writes:
> how can I copy an object?
> E.g.:
> v0 = OBJ_NEW('IDLgrVolume')
> v1 = v0
>
> v1 only contains only a reference to v1, so I cannot use v0 and v1 in
> different model trees, which is what I need.
> I was looking for something like
> v1 = OBJ_NEW( v0 ), but this doesn't work.
Copying objects is one of those things that come up
over and over again in object programming. In practice
it seems difficult, because you have the problem of
"deep" copying (I.e., pointers to pointers, other objects
with pointers, etc.) You start thinking about recursion,
then--of course--you get totally confused.
You have a page full of diagrams with arrows
going every which way, your migraine headache starts up
again, and you begin to think, "Oh, hell, I'll just go
back to thinking about where to invest my money in the
stock market." It seems so much easier.
Even if you call up RSI and ask the experts there,
they give you the same old song and dance, and you
work on it some more until your eyes cross and your
backhand has disappeared from disuse.
But it still never works right...until you discover
the secret. :-)
Here it is (already published in this newsgroup space,
I guess, although I must have missed it, and never with
as much unnecessary build-up as I'm going to give it).
RSI has already done the work for you!!
Seriously. The secret is SAVE and RESTORE. Here is the
secret to copying an object:
newobject = oldobject
Save, newobject, Filename='secret.sav'
Restore, 'secret.sav'
Done. Do you believe it? I know I didn't. But it works
like a charm.
Here is a function, then, to copy objects:
;******************************
;* A function to copy objects *
;******************************
FUNCTION OBJ_COPY, obj, TEMPDIRECTORY=temp
CATCH, error
IF (error NE 0) THEN $
BEGIN
CATCH, /CANCEL
RETURN, OBJ_NEW ()
ENDIF
IF (NOT OBJ_VALID (obj)) THEN MESSAGE, 'Invalid object reference.'
CD, CURRENT=origDir
IF (N_ELEMENTS (temp) NE 0) THEN CD, temp
newobj = obj
SAVE, newobj, FILENAME='temp.sav'
RESTORE, 'temp.sav'
FILE_DELETE, 'temp.sav'
IF (N_ELEMENTS (temp) GT 0) THEN CD, origDir
RETURN, newobj
END
Cheers,
David
--
David W. Fanning, Ph.D.
Fanning Software Consulting, Inc.
Phone: 970-221-0438, E-mail: david@dfanning.com
Coyote's Guide to IDL Programming: http://www.dfanning.com/
Toll-Free IDL Book Orders: 1-888-461-0155
|
|
|