深拷贝和浅拷贝
浅拷贝:简单的赋值操作
深拷贝:在堆区重新申请空间,进行拷贝操作
例1:
#include<iostream>
using namespace std;
class person
{
public:
person()
{
cout << "默认构造函数" << endl;
}
person(int age)
{
m_Age = age;
cout << "有参构造函数" << endl;
}
~person()
{
cout << "析构函数" << endl;
}
int m_Age;
};
int main()
{
person p1(18);
cout << "p1的年龄为:" << p1.m_Age << endl;
person p2(p1);
cout << "p2的年龄为:" << p2.m_Age << endl;
system("pause");
return 0;
}
虽然没有写拷贝构造函数,但是编译器会自动写拷贝构造函数,进行浅拷贝
例2:
#include<iostream>
using namespace std;
class person
{
public:
person()
{
cout << "默认构造函数" << endl;
}
person(int age,int height)
{
m_Age = age;
m_Height = new int(height);//new出来的变量需要用指针来接收
cout << "有参构造函数" << endl;
}
~person()
{
if (m_Height != NULL)//判断m_Height是否指向空,若不是空则delete,并指向空
{
delete m_Height;
m_Height = NULL;
}
cout << "析构函数" << endl;
}
int m_Age;
int* m_Height;
};
int main()
{
person p1(18,160);
cout << "p1的年龄为:" << p1.m_Age <<"p1的身高为:"<<*(p1.m_Height) << endl;
person p2(p1);
cout << "p2的年龄为:" << p2.m_Age<<"p2的身高为:"<<*(p2.m_Height) << endl;
system("pause");
return 0;
}
只打印了一个析构函数,并且崩溃了。
原因:
这是浅拷贝的问题,因为new是堆区开辟的,先进后出,所以先p2执行析构函数,if成立,释放p2的m_Height的内存,后p1执行析构函数,因为p1的m_Height未被释放(两个m_Height指针是独立的,但因为p2的m_Height是拷贝于p1的m_Height,所以指向同一个空间),所以p1的m_Height也被if释放内存,又因为该内存已经被p2的if释放,所以崩溃。
需要自己实现深拷贝来解决浅拷贝带来的问题
#include<iostream>
using namespace std;
class person
{
public:
person()
{
cout << "默认构造函数" << endl;
}
person(int age, int height)
{
m_Age = age;
m_Height = new int(height);//new出来的变量需要用指针来接收
cout << "有参构造函数" << endl;
}
person(const person& p)
{
cout << "拷贝构造函数" << endl;
m_Age = p.m_Age;
m_Height = new int(*p.m_Height);
}
~person()
{
if (m_Height != NULL)//判断m_Height是否指向空,若不是空则delete,并指向空
{
delete m_Height;
m_Height = NULL;
}
cout << "析构函数" << endl;
}
int m_Age;
int* m_Height;
};
int main()
{
person p1(18, 160);
cout << "p1的年龄为:" << p1.m_Age << "p1的身高为:" << *(p1.m_Height) << endl;
person p2(p1);
cout << "p2的年龄为:" << p2.m_Age << "p2的身高为:" << *(p2.m_Height) << endl;
system("pause");
return 0;
}
深拷贝里的赋值语句为:m_Height=new int(*p.m_Height);
编译器默认实现的浅拷贝为:m_Height=p.m_Height;
需要重新开辟一个内存,才不会重复释放同一块内存
潜孤云: 干货满满!我也写了一篇获取【大厂面试真题解析、核心开发学习笔记、最新全套讲解视频、实战项目源码讲义、学习路线简历模板】的文章
临界三极管: 还是不会快点出手把手教程
Kwan的解忧杂货铺: 你的文章总是让我拓展了视野,增长了见识,每篇博文都是知识的瑰宝,我真的很喜欢你的风格,感谢你的专业分享。期待你的下一次精彩分享。
boy1886: userservice: ribbon : NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule 大佬 问下 这段我早在yml写的时候 显示波浪号,没有ribbon : NFLoadBalancerRuleClassName 的 这个怎么办啊
@katoumegumi: 停更了