浅拷贝
浅拷贝:就是简单的赋值操作。
浅拷贝问题:如果有指针指向堆区内存时,不同对象的指针成员指向同一块堆区内存,当对象释放时,该堆区内存会被释放两次。当一个对象修改堆区内存是,另一个对象也随之变化
class A
{int num;int *p;
public:A() {this->num = 0;p = nullptr;cout << "无参构造" << endl; }A(int a) { this->num = a;p = new int[num];cout << "有参构造" << endl; }( const A &other ) {p = other.p;num = other.num;}
~A(){if (p) delete[]p;}
};
深拷贝
深拷贝:申请相同大小的堆区内存,保证两个对象堆区的值相同
class A
{int num;int *p;
public:A() {this->num = 0;p = nullptr;cout << "无参构造" << endl; }A(int a) { this->num = a;p = new int[num];cout << "有参构造" << endl; }A( const A &other ) {num = other.num;p = new int[num]; //保证内存大小相同for (int i = 0 ;i < num;i++){p[i] = other.p[i]; //保证数据相同}cout << "拷贝构造" << endl;}~A(){if (p) delete[]p;}
};