C++深拷贝与浅拷贝

mac2026-08-27  10

浅拷贝:简单的赋值拷贝操作 深拷贝:在堆区重新申请空间,进行拷贝操作

#include <iostream> #include<string> using namespace std; class Person { public: Person() { cout << "Person的无参构造函数" << endl; } Person(int age,int height) { mage = age; mheight = new int(height); cout << "Person的有参构造函数" << endl; } //拷贝构造函数,自己实现拷贝构造函数,解决浅拷贝问题 Person(const Person &p) { mage = p.mage; cout << "Person的拷贝构造函数" << endl; mheight=new int(*p.mheight);//用深拷贝解决浅拷贝问题。 } ~Person() { if (mheight != NULL) { delete mheight; mheight = NULL; } cout << "person的析构函数" << endl; } int mage; int *mheight; }; void test01() { Person p1(18,160); cout << "p1的年龄为:" << p1.mage<<"身高为:"<<*p1.mheight<<endl; Person p2(p1);//如果提供编译器提供的拷贝函数,会做浅拷贝操作,最后会导致堆区的内存重复释放 cout << "p2的年龄为:" << p2.mage << "身高为:" << *p2.mheight << endl; } int main() { test01(); system("pause"); return 0; }

浅拷贝会使堆区内存释放两遍导致出错。 用深拷贝解决浅拷贝带来的出错问题。

来源:黑马程序员

最新回复(0)