ICloneable and releasing memory

  • Thread starter Thread starter ib
  • Start date Start date
I

ib

ICloneable::Clone returns a new instance of the object being cloned.
However, it seems possible that the garbage collector could release this
memory before the calling function receives a reference to the memory. If
this can occur then it introduces an error that would only occur at random
times. Is this really a problem or does .NET take the necessary steps to
ensure the memory is first referenced by the calling function before the
garbage collector gets a chance to check the memory?

Thanks,

Ian
 
Hi Ian,

I don't see why returning a new object from a method named, "Clone" would be
any different, in terms of GC, from returning a new object from any other
method. What exactly is your concern here?
 
ib said:
ICloneable::Clone returns a new instance of the object being cloned.
However, it seems possible that the garbage collector could release this
memory before the calling function receives a reference to the memory. If
this can occur then it introduces an error that would only occur at random
times. Is this really a problem or does .NET take the necessary steps to
ensure the memory is first referenced by the calling function before the
garbage collector gets a chance to check the memory?

Why would the memory have to be referenced "by the calling function"?

There is a reference to the memory on the stack, either as a local
variable in the Clone method, as a return value from the Clone method,
or as a local variable in the calling method. Since the GC walks the
stack as one of its ways of determining what is currently in use, it
will find a reference to the memory throughout the cloning process.

It's no different from new-ing an object and returning it from any
other method.
 
Back
Top