Qt object deep copy and shallow copy examples

Article directory

In Qt, object copying can be divided into two types: shallow copy (Shallow Copy) and deep copy (Deep Copy). Below is sample code and explanation for both types of copy:

1. Shallow Copy

Shallow copy refers to directly copying the values ​​of member variables of an object to another object. Both objects share the same data. If the data of the original object changes, the data of the copied object will also change. Many classes in Qt use shallow copy by default.

class Person {
    
    
public:
    QString name;
    int age;
};

Person p1;
p1.name = "Alice";
p1.age = 25;
Person p2 = p1; // 浅拷贝,p2与p1共享相同的数据

In the above code, p1 and p2 are Person objects of the same type. When shallow copying is performed, the name and age member variables of p2 will be copied directly from p1. This means that both p1 and p2 point to the same actual data, and if you change the data of one of the objects, the data of the other object will change accordingly.

2. Deep Copy:

Deep copy refers to creating a new object and copying the values ​​of the member variables of the original object to the new object. The two objects have their own independent copies of data and do not affect each other.

class Person {
    
    
public:
    QString name;
    int age;
};

Person p1;
p1.name = "Alice";
p1.age = 25;
Person p2;
p2.name = p1.name; // 深拷贝,p2有自己的name数据副本
p2.age = p1.age;   // 深拷贝,p2有自己的age数据副本

In the above code, p1 and p2 are Person objects of the same type. When performing a deep copy, you need to copy the member variables of p1 to the member variables of p2 one by one. In this way, both p1 and p2 have independent copies of the data, and changes between them do not affect each other.

It should be noted that for some classes in Qt, they have implemented copy constructor and assignment operator overloading to correctly handle deep copies. However, for custom classes or when dealing with raw pointers, you need to manually implement deep copy logic to ensure data independence.


Guess you like

Origin blog.csdn.net/m0_45463480/article/details/132582704