开发者

What does it mean to clone() an object?

What is object cloning in vb6 or java? In what situation do we use a clone? What does cloning objects mean? Can any one tell me with example pl开发者_开发知识库ease.


Cloning is actually copying the object data into a new object.

This example doesn't clone the data:

Foo p = new Foo();
Foo o = p;

If Foo has a member a and you change p.a then o.a also changes because both p and o point to the same object.

However,

Foo p = new Foo();
Foo o = p.Clone();

In this case if you change p.a then o.a remains the same because they actually point to separate objects.

There are actually two different ways you can clone: shallow clone or deep clone.

A shallow clone just makes a new object and copies the members into the new object. This means that if one of the members is actually a pointer to another object then that object will be shared between the old object and new object.

A deep clone actually goes through and clones all the members into the new object. That way the objects are complete copies of all the data.


Generaly speaking objects are passed by reference. So if you say $objB=$objA you are not getting a new object; you are getting a new name for the same object. However, if you say $objB= clone $objA you get a copy of $objA. In the first case, whatever you do to $objB also happens to $objA. In the 2nd case, $objB is independent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜