For some types of class, if we could avoid the copy operation, it will be great advantage.
Sometimes, copy cost a lot.
It’s not a good way to use pointer to avoid copy operation. It’s unsafe.
What if we want the attribute of polymiorphism and reduce the cost of copy ?
The answer is Handle which is a special class.
We use count to avoid copying. The count can not be a part of handle. If we do that, each handle have to know others handles’ location(it’s easy for us to get address of members who are in the same class). Only we do that, we could update the count correctly. We also could not let the count be a part of objects. Becasue we have to rewrite the type of class which have already existed.
So, we define a new type of class to store the count and object.
In this scheme, we meet a weak point of the mechanisim that we have to attach the handler onto the class (in our demo, it’s @UPoint).
It’s not convenient for us to use that scheme for different types of class which are inhiret from base class.
We sperate data and reference count by changing our handle into this:
Here is the other and better implementation for handle.
In this implementation, we use a very cool teachnology – Copy On Write(COW). You may have see this teachnology in Operating System which use it to implement a very important function –
You will get this output :)
Photo by Jason Leaster in XiangTan University
作者: Jason Leaster
本文采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可