1.浅拷贝
简单的赋值拷贝操作
2.深拷贝
在堆区重新申请空间,进行拷贝操作
class Person { public: //无参(默认)构造函数 Person() { cout << "无参构造函数!" << endl; } //有参构造函数 Person(int age ,int height) { cout << "有参构造函数!" << endl; m_age = age; m_height = new int(height); } //拷贝构造函数 Person(const Person& p) { cout << "拷贝构造函数!" << endl; //如果不利用深拷贝在堆区创建新内存,会导致浅拷贝带来的重复释放堆区问题 m_age = p.m_age; m_height = new int(*p.m_height); } //析构函数 ~Person() { cout << "析构函数!" << endl; if (m_height != NULL) { delete m_height; } } public: int m_age; int* m_height; }; void test01() { Person p1(18, 180); Person p2(p1); cout << "p1的年龄: " << p1.m_age << " 身高: " << *p1.m_height << endl; cout << "p2的年龄: " << p2.m_age << " 身高: " << *p2.m_height << endl; } int main() { test01(); system("pause"); return 0; }
3.智能指针
#pragma once class Smart_ptr { friend class ChasPtr; private: int* ip; size_t use; //计数 Smart_ptr(int *p):ip(p),use(1){} ~Smart_ptr() { delete ip; } }; class ChasPtr { public: ChasPtr(int *p,int i):ptr(new Smart_ptr(p)),val(i){} ChasPtr(const ChasPtr& orig) :ptr(orig.ptr), val(orig.val) { ++ptr->use; } int* get_ptr()const { return ptr->ip; }; int get_int()const { return val; } void set_ptr(int* p) { ptr->ip = p; }; void set_int(int i) { val = i; }; int get_ptr_val()const { return *ptr->ip; }; void set_ptr_val(int val)const { *ptr->ip = val; }; ChasPtr& operator=(const ChasPtr&); ~ChasPtr() { if (ptr->use-- == 0) delete ptr; } private: //int* ptr; Smart_ptr* ptr; int val; }; ChasPtr& ChasPtr::operator=(const ChasPtr&rhs) { ++rhs.ptr->use; if (--ptr->use == 0) delete ptr; ptr = rhs.ptr; val = rhs.val; return *this; }
int obj = 1; ChasPtr ptr1(&obj, 42); ChasPtr ptr2(ptr1); cout << ptr1.get_ptr_val() << " , " << ptr1.get_int() << endl; cout << ptr2.get_ptr_val() << " , " << ptr2.get_int() << endl; ptr2.set_ptr_val(10); ptr2.set_int(50); cout << ptr1.get_ptr_val() << " , " << ptr1.get_int() << endl; cout << ptr2.get_ptr_val() << " , " << ptr2.get_int() << endl;