What does it mean to clone() an object? - clone

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 please.

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.

Related

How to make a separate copy of an object in Perl 6?

I don't fully understand the docs, so I've tried clone, and it seems if there is an attribute of a mutable class, it can be changed in the new object using the old one (and that's what I don't want). How to make them (i.e. the copy and the original) fully separate?
class A {
has #.a;
}
my A $x = A.new;
my A $y = A.new;
$x.a = 1, 2;
$y = $x.clone;
$x.a.push(4);
say $y.a; # [1 2 4]
The default clone inherited from Mu is shallow, as documented. This means that it will only copy the object itself, but not anything the object references. It is possible to override clone to have your preferred semantics, which is probably the best thing to do here.
One useful thing to know in doing this is that clone takes named parameters and uses them to assign to properties of the cloned object. This is worth knowing because:
One should make sure to handle this when overriding clone, to avoid surprises to users of the overridden clone method who use this feature
One can use this when overriding clone to succinctly opt in to cloning of a particular array or hash attribute
Thus for the case in the question, writing:
class A {
has #.a;
method clone() {
callwith(:#!a, |%_)
}
}
Will result in the output [1 2] as presumably desired. How does it work?
The |%_ just passes on any tweaks the caller of this clone method specified
:#!a is short for a => #!a
callwith calls the inherited clone (from Mu in this case)
Assignment, not binding, semantics are used on #!a in the target object (just as during object construction), resulting in a copy of the array
This shortcut works for hash attributes too. For an attribute containing another object, it'd look like callsame(x => $!x.clone).

move semantics with temps allocated with new

I'm just wondering if move semantics are restricted to syntax style B.
More specifically, with style B the object is created on the stack and moved. With style A, the object is created on the heap, but it seems can't be moved.
The question very specifically is, can you use move semantics such that the temp is created with NEW? If so, how?
//move c'tor
A(A&& other) : num(other.num), s(other.s){
other.num = 0;
other.s = nullptr; //dyn alloc obj
}
If you do this, it doesn't work (syntax style A).
A a2(new A("blah")); //error
A a2(move(new A("blah"))); //error
This is ok (syntax style B)
A a2(A("blah")); //uses c'tor once
A a2(move(A("blah"))) //uses c'tor followed by move c'tor
You seem to be confused about a number of things, so I'll try to shed some light. You probably know most of this already.
Move semantics were designed to allow objects to transfer ownership of their data to another object. This was motivated largely to avoid copying from temporary objects that didn't need it.
The move constructor is much like the copy constructor, A(const A&), but only accepts a non-const xvalue of the same type, A(A&&) (think of it as an expiring value). Therefore, this constructor can be invoked when given something like a return value from a function or a variable moved via std::move.
Now, the function std::move in itself is a bit of a misnomer, it doesn't actually do anything. All it does it cast a T or T& into a T&&.
To address your question directly, nothing I've mentioned is specific to where the moving object is located, but it is specific about the types. A("blah") calls the constructor with automatic memory and returns that A. new A("blah") on the other-hand calls the constructor with dynamic memory and returns a pointer to that A, ergo an A*. So your syntax A is not trying to invoke the move constructor, but another constructor like A(A*).
To move from an object referenced by a pointer, all you need to do is derefence and move:
A* a1 = new A("blah");
A a2(std::move(*a1));
There's nothing stopping you from defining a constructor like A(A*), but that shouldn't be needed and isn't recommended for using move semantics.
Also, your syntax B comments are incorrect; both are a value-constructor A("blah") followed by the move-constructor A(A&&); the std::move doesn't add anything here.

Swift deinit is being called but object still not deallocating

In swift I am getting the deinit function to print out a line saying that the object has been de initialized, but the object is still being reported as live in Instruments, allocations tool. I didn't think this was even possible. Is there a way to find out why it's not being freed? Or is there a way to find out what child objects could be holding it up?
Update: For Swift 4, see the additional note at the end.
Warning: This answer goes into some detail about the way the Swift runtime is implemented. The information here does not affect how you write code in Swift, except in some advanced scenarios. The main point is that from your point of view as a programmer, once deinit is called, the object is dead to you and you cannot use it any more.
The reason the memory is not freed is that objects in Swift are not necessarily deallocated (freed) straight away when they are deinited. Weak references to an object will cause the 'husk' of the object to stay allocated (in memory - you still can't use it!) until all the weak references have been zeroed.
Weak references in Swift are not zeroed immediately when the object is deinited, but they will be zero the next time they are accessed. That is, Swift zeroes weak references lazily. Here's an example:
public class MyClass {
}
var object = MyClass()
weak var weakObject = object
print (weakObject) // Points at a MyClass instance
object = MyClass()
// A: weakObject is not yet nil
print(weakObject) // prints 'nil'
// B: now weakObject is nil
After assigning object to a new instance (line 6), you would think that the weak reference to the original object would be zero, but it's not (yet). The object is deinited but stays allocated (in memory) until all the weak references are gone. At point A, a weak reference still exists, it's only on the next line when you try to evaluate the weak reference that Swift checks and notices that the object it references is deinited, so it zeroes the weak reference and then passes it to the print function to be printed. This mechanism needs the object's empty husk to remain allocated until all the weak references are gone. It is called a husk because all of its properties have been zeroed and released in deinit so it doesn't keep anything else alive (the amount of memory for an object is quite small, just enough to store its internal headers and members).
Why and how?
Each object has an internal weak reference count instead of a list of references that need to be zeroed. This is much quicker and less resource intensive to deinit because zeroing a list of weak references in a thread-safe way requires quite a long atomic/synchronized operation.
When the strong reference count reaches zero, deinit is called and the object enters the deallocating state. The run-time keeps the memory allocated because it needs to check the state of the object whenever a weak reference is accessed. Once all weak references have been accessed and zeroed (the weak reference count is zero), the memory will be freed and deallocation is complete.
Take a look at the implementation of swift_weakLoadStrong from the swift source code - this is the code that is inserted when a weak reference is accessed and made strong (for example to be assigned to a strong reference or passed into a function etc.). I have abbreviated it below. Look at the original code on github to see the full complexity of loading a weak reference:
if (object == nullptr) {
__atomic_store_n(&ref->Value, (uintptr_t)nullptr, __ATOMIC_RELAXED);
return nullptr;
}
if (object->refCount.isDeallocating()) {
__atomic_store_n(&ref->Value, (uintptr_t)nullptr, __ATOMIC_RELAXED);
SWIFT_RT_ENTRY_CALL(swift_unownedRelease)(object);
return nullptr;
}
auto result = swift_tryRetain(object);
__atomic_store_n(&ref->Value, ptr, __ATOMIC_RELAXED);
return result;
You can see that the object husk still exists in memory, and the mechanism that loads the weak reference (i.e. when you access it in your code) checks if it is deallocating, and if so it zeroes the weak reference, calls swift_unownedRelease to decrement the weak reference count and free the object if the count has reached zero, and returns nullptr (nil).
Swift 4 Update
Since Swift 4, weak references have an improved implementation that means the object husk no longer needs to hang around. Instead a small side-table is used and weak references actually point to that instead. The side-table contains a pointer to the real object and Swift knows to follow this pointer when accessing weak references. For a much more detailed explanation, read this great blog post from Mike Ash.
My suspicion would be that you are looking at different objects. Why do you believe that the object that called deinit is the same object that you're seeing in Instruments? Having more instances than you think you do (or just looking at the wrong one) is one of the most common causes of these kinds of confusion.
Is your deinit only the print statement, or are you doing anything else? In particular, are you doing anything that might accidentally retain you again? (I can't remember if that's well-defined behavior.)
Make dure you don't have any strong relationships with another object. Imagine the following:
class A {
var b: B
}
class B {
var a: A
}
a.b = xxx
b.a = yyy
If A holds a strong reference to B and B a strong reference to A, you create a strong reference cycle between them, and setting
a = nil
won't call deinit because it holds a strong reference to b. You either set a.b to nil, or use the weak references (weak keyword) to solve this.
check apple's documentation here for more details

Find all references to an object in Lua

I have a memory leak in the Lua part of my application. For whatever reason, my object is not getting deleted when it should (even when I call collectgarbage("collect")). I assume this means I have a dangling reference somewhere.
So how may I obtain a list of where various references to an object reside? For example:
obj = MyObject()
ref = obj
tbl = {obj}
obj = nil
print(getreferences(obj)) -- should print something like _G.ref, _G.tbl[1]
I would simply write my own function for this, but it would not be able to find references contained inside of closures. Any advice?
There's a tool to traverse the whole Lua universe. See http://lua-users.org/lists/lua-l/2006-07/msg00110.html

Why does String::sub!() change the original of a cloned object in Ruby?

I have a struct in my Ruby code that looks somewhat like this
Parameter = Struct.new(:name, :id, :default_value, :minimum, :maximum)
later, I create an instance of this struct using
freq = Parameter.new('frequency', 15, 1000.0, 20.0, 20000.0)
At some point, I need an exact duplicate of this struct, so I call
newFreq = freq.clone
Then, I change newFreq's name
newFreq.name.sub!('f', 'newF')
Which, miraculously, changes freq.name, too!
A simple assignment like newFreq.name = 'newFrequency' does not change freq.
Is this the way this is supposed to work?
Edit: Is it a good idea to use a class instead of a struct and overload clone to make a deep copy?
newFreq is a shallow copy of freq. That means that each of the references stored inside of newFreq points to the object as the ones stored in freq. You can change where the references point independantly (newFreq.name = newFreq.name.sub 'f','newF'), but if you call a method that mutates the object, both newFreq and freq will be affected.
See also http://en.wikipedia.org/wiki/Object_copy
The Object#clone method performs shallow copy. You need deep copy to get the job done.
Follow this link to learn about deep copy in Ruby.

Resources