Clone function

overview

The Clone function is a computer function for duplication. In programming , in addition to customizing a copy constructor to realize object replication , a clone function can also be implemented . This requires a hidden copy constructor implemented by the compiler, which is more worry-free.

Chinese name clone function
Foreign name clone
Department of affiliation informology

basic introduction

In C++ , to copy an object, in addition to customizing a copy constructor to realize object copy, you can also implement a clone function. This requires a hidden copy constructor implemented by the compiler, which is more worry-free.

The principle behind it is C++'s prototype (Prototype) mode: use the prototype instance to specify the type of object to be created, and create new objects by copying these prototypes.

The Prototype mode provides an interface (Clone) for creating new objects through existing objects. The implementation of Clone is related to the specific language, and it is implemented in C++ through the copy constructor.

Note: The clone function is virtual and cannot be inlined.

Sample code:

#include "stdafx.h"
#include <iostream>
 
class CA
{
public:
    int value;
    CA* clone() const { return new CA( *this );}
    //仅一个构造函数
    CA(int a ){value=a;}   
};
 
int _tmain(int argc, _TCHAR* argv[])
{
    CA* objA=new CA(10);
    CA* objtemp=objA->clone();
    delete objA;
    std::cout<<objtemp->value;
    delete objtemp;
    return 0;
}

The application scenario of the Prototype mode is that you get a Base *, which points to a Derived object, and you want to clone the Derived object, but the specific type of Derived is not written in the code, because there are many derived classes. In this case, you It is impossible to use the constructor, so the Prototype mode is needed.

The role of the prototype pattern

1. Basically, if you need to get an instance from the instance of A that has the same content as A but does not interfere with each other, you need to use the prototype mode.

2. Use the prototype instance to specify the type of object to be created, and create new objects by copying these prototypes. This is actually similar to (but not the same as) the function of the copy constructor of C++ . In fact, it is to dynamically extract the runtime state of the current object .

Clone method

About the clone method

Before explaining the clone method, you need to have a preliminary understanding of value passing and reference passing

It should be noted that the third

(1) The basic data type is passed by value, and the modification of the formal parameter will not affect the actual parameter ;

(2) The reference type is passed by reference, the formal parameter and the actual parameter point to the same memory address (the same object), so the modification of the parameter will affect the actual object;

(3) String, Integer, Double and other immutable types are specially treated, which can be understood as passing values, and the final operation will not modify the actual parameter object. (It is still passed by reference in essence, but these types are immutable classes, which can be understood as passing by value)

After having a preliminary understanding of passing by value and passing by reference, we start to explain the clone method.

Steps to use the clone method

1. The class that implements clone first needs to inherit the Cloneable interface. This interface is an identification interface without any interface method

2. Override the clone method of the Object class in the class

3. Call super.clone in the clone method

In this way, a copy of an Object object that implements the clone class can be obtained, but there is a problem, what if there is still a reference type in this class? Now we will explain shallow copy and deep copy.

shallow copy and deep copy

1. The members in the class are all basic data types, using shallow copy

2. Members in the class have reference types (at this time, it should be noted that immutable types such as String, Integer, and Double are treated specially and not regarded as reference types), and deep copy is used

The use of shallow copy and deep copy depends on the actual situation

Shallow copy: All variables of the copied object contain the same value as the original object, and reference variables still point to the original object

Deep copy: All variables of the copied object contain the same value reference as the original object, and the reference variable points to the new variable of the copied object

Advantages of the prototype pattern

1. Why not use new to create new objects directly, but use the prototype mode?

First of all, using new to create a new object cannot obtain the runtime state of the current object. Secondly, even if a new object is new, the efficiency of copying the value of the current object to the new object is not as high as that of the prototype mode.

2. Why not use the copy constructor directly, but use the prototype mode?

The prototype mode and the copy constructor are different concepts. The classes involved in the copy constructor are known, and the classes involved in the prototype mode can be unknown.

The new object generated by the prototype pattern may be a derived class. The new object generated by the copy constructor can only be the class itself. The prototype mode describes a general method (or concept), no matter how it is implemented, while the copy construction describes a specific implementation method.

    class base  
    {  
      public :   
      base();  
      base(base &obj);  
      virtual  ~base();  
      virtual base *clone() { return new base(*this) ; };  
    };  
    class derived : public base  
    {  
      public :   
      derived();  
      derived(  derived &);  
     virtual base *clone(){return new derived (*this); }  
    ....  
    };  

    base *obj1 = new base ;   
    base *obj2 = new derived ;//基类指针指向派生类对象,怎样用基类指针创建一个新的派生类对象?? 用基类的拷贝构造函数显然不行。  
    base *obj3 = obj1 .clone();  
    base *obj4 = obj12.clone();  

Applicable scene

1. Resource optimization scenario

Class initialization needs to consume a lot of resources, including data, hardware resources, etc.

2. Scenarios with performance and security requirements

Generating an object through new requires very cumbersome data preparation or access rights, so you can use the prototype mode.

3. Scenarios where one object has multiple modifiers

When an object needs to be accessed by other objects, and each caller may need to modify its value, you can consider using the prototype mode to copy multiple objects for the caller to use.

shortcoming

1. Equipping the cloning method requires overall consideration of the functions of the class. This is not difficult for brand new classes, but it is not necessarily easy for existing classes, especially when a class references indirect objects that do not support serialization, or references When a loop structure is included.

2. To implement the prototype mode, each derived class must implement the Clone interface.

3. Escape the constraints of the constructor.


References

Guess you like

Origin blog.csdn.net/aliyonghang/article/details/132218245