ICloneable and releasing memory

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
 
D

Dave Sexton

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?
 
B

Bruce Wood

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top