Introduction to deep copy and shallow copy in C++

For basic types of data and simple objects, copying between them is very simple, which is to copy the memory bit by bit. For example:

    class Base{
    public:
        Base(): m_a(0), m_b(0){ }
        Base(int a, int b): m_a(a), m_b(b){ }
    private:
        int m_a;
        int m_b;
    };
    int main(){
        int a = 10;
        int b = a;  //拷贝
        Base obj1(10, 20);
        Base obj2 = obj1;  //拷贝
        return 0;
    }

Both b and obj2 are initialized by copying. Specifically, the data in the memory where a and obj1 are located is copied to the memory where b and obj2 are located according to the binary bit (Bit). This default copy behavior is a shallow copy. , which is very similar to the effect of calling the memcpy() function.

For simple classes, the default copy constructor is generally sufficient, and we do not need to explicitly define a copy constructor with similar functions. But when the class holds other resources, such as animals

Guess you like

Origin blog.csdn.net/shiwei0813/article/details/132996144