19. Object construction (below)

    Two special constructors:

No-argument constructor: A constructor with no arguments.

Copy constructor: A constructor whose parameter is const class_name& (the current class object).

No-argument constructor, when no constructor is defined in the class, the compiler provides a no-argument constructor by default, and its function body is empty. If the function body is empty, there is at least one no-argument constructor in the class.

       Note: The default constructor is only provided if there is no constructor at all.

Copy constructor, when no copy constructor is defined in the class, the compiler provides a copy constructor by default, which simply copies the value of member variables.

The meaning of the copy constructor: It is compatible with the initialization method of the C language, and the initialization behavior can conform to the expected logic.

 Shallow copy: The physical state of the object after the copy is the same. (the pointer itself, the same pointer may be released twice)

 Deep copy: The logical state of the object after the copy is the same. (The value pointed to by the pointer is assigned, and the pointer itself is different)

     The copy constructor provided by the compiler only makes a shallow copy.

Test(const Test& t)

{     i=t.i;

      j=tj;

     p=new int; // p, *p are members of t2

     *p=*t.p;   }

Test t2=t1; // t1 replaces the t above

When do you need a deep copy?

    The members in the object refer to the resources in the system: the members refer to the dynamic memory space, the members open the files in the external memory, and the members use the network ports in the system.

General principle: To customize the copy constructor, it is necessary to implement deep copy.

IntArray::IntArray(const IntArray& obj)
{
m_length=obj.m_length;
m_pointer=new int[obj.m_length];
for(int i=0;i<obj.m_length;i++)
{
m_pointer[i]=obj.m_pointer[i];
}

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325885570&siteId=291194637