C ++ study notes Lesson 19 deep copy

Study Notes content from: Ditai Software College Tangzuo Lin teacher's video, I appreciate your guidance

Special constructor

No argument constructor
when the definition is not a class constructor, the compiler provides a default constructor with no arguments, and the function body is empty

Copy constructor
when the class is not defined when the copy constructor, the compiler provides a default copy constructor, simply copying a value of a member variable

Therefore, the following class definition is not empty because there are no hidden argument constructor and copy constructor provided by default
class Test {};

Initialization and assignment

In C ++, initialization and assignment is not the same, it will trigger initialization constructor, and assignment does not

Copy constructor

1. Format: claas_name (const & Another class_name) {}
2. Significance: C language compatible initialized

The copy constructor deep and shallow copy copy

1. shallow copy: copies of the same physical state of the object after
2 deep copy: The same logic state after the copy of the object

PS: copy constructor provided by the compiler only shallow copy

When the need for deep copy

1. The members of the object refer to the resources in the system
2. The dynamic memory space pointed member
3. The member opened file in the external memory
4. The port member used in the system
5 ...

The sample program:

class Array
{
private:
    int* m_data;
    int m_length;
public:
    Array()
    {
        data = new int[5];
    }
    
    Array(const Array& another)
    {
        /*
         * 浅拷贝:
         * this->m_data = another.m_data;
         * this->length = another.length;
         * 
         * 深拷贝:
         * 
         * this->m_data = new int[5];
         * this->length = another.length;
       */
    }
    
    ~Array()
    {
        delete[] this->m_data;
    }
};

Deep copy is not performed, then the destructor will occur when re-releasable with a memory space, will mistakes

Published 11 original articles · won praise 0 · Views 77

Guess you like

Origin blog.csdn.net/u012321968/article/details/104450358