In-depth understanding of C++ deep copy and shallow copy, the use of copy constructors, overloaded operators and destructors, etc.

1. Understanding deep copy and shallow copy

Deep copy directly copies the content, etc. For example, a shallow copy of an object only copies the address, while a deep copy requires a new object to copy the result , and this deep copy has heaps, files, When system resources are reduced, such operations need to be performed.
The reason for doing this is because:

  • When there are pointers in the data members, if a simple shallow copy is used, the two pointers in the two classes will point to the same address. When the object is about to end, the destructor will be called twice, causing the pointer to hang.

2. Copy constructors, overloaded operators and destructors of classes in C++

The copy constructor is used :

  • The copy constructor in C++ only copies the value of the pointer, which is a shallow copy. We manually create a new dynamic memory address for the instruction in the copy constructor, and then copies the value, which is a deep copy.
class A
{
    
    
public:
    A(int _size) : size(_size)
    {
    
    
        data = new int[size];
    } // 假如其中有一段动态分配的内存

    A(const A& a){
    
    
        this->data=new int[a.size];
        for(int i=0;i<a.size;++i){
    
    
            this->data[i]=a.data[i];
        }
    }

    A& operator=(const A &a){
    
    
        //实现重载运算符
        if(this!=&a){
    
    
//            this->data=a.data;
            //申请空间并拷贝内容
            this->data=new int[a.size];
            for(int i=0;i<a.size;++i){
    
    
                this->data[i]=a.data[i];
            }

        }
    }
    ~A()
    {
    
    
        delete [] data;
    } // 析构时释放资源

    //打印变量值
    void print(){
    
    
        for(int i=0;i<size;++i){
    
    
            std::cout<<data[i]<<std::endl;
        }
    }
private:
    int* data;
    int size;
};

int main()
{
    
    
    A a(5), b = a;
    a.print();
}

Realization effect:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_42295969/article/details/127253417