123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- //4、2、5 深拷贝与浅拷贝
- //深拷贝是面试经典问题,也是常见的一个坑
- //浅拷贝:简单的复制拷贝操作
- //深拷贝:在堆区重新申请空间,进行拷贝操作
- //浅拷贝带来的问题就是堆区的内存重复释放
- //浅拷贝的问题要用深拷贝进行解决
- #if(0)
- #include <iostream>
- class Person
- {
- public:
- //无参默认构造函数
- Person()
- {
- std::cout << "Person的默认构造函数调用" << std::endl;
- }
- //有参构造函数
- Person(int age ,int height)
- {
- m_Age = age;
- m_Height = new int(height);
- std::cout << "Person的有参构造函数的调用" << std::endl;
- }
- //拷贝构造函数
- //自己实现拷贝函数 解决浅拷贝带来的问题
- Person(const Person& p)
- {
- std::cout << "Person拷贝构造函数的调用:" << std::endl;
- m_Age = p.m_Age;
- //m_Height = p.m_Height; 编译器默认实现就是这行代码
- //深拷贝操作
-
- m_Height = new int(*p.m_Height);
-
- }
- ~Person()
- {
- //析构代码的用途是将堆区开辟的代码数据做一个释放的操做
- if (m_Height != NULL)
- {
- delete m_Height;
- m_Height = NULL;
- }
- std::cout << "Person的析构函数的调用" << std::endl;
- }
- int m_Age; //年龄
- int* m_Height; //身高
- };
- void test01()
- {
-
- Person p1(18,160);
- std::cout << "P1的年龄为:" << p1.m_Age << "身高为:" << *p1.m_Height << std::endl;
-
- Person p2(p1);
- std::cout << "P2的年龄为:" << p2.m_Age << "身高为:" << *p2.m_Height << std::endl;
- }
- int main()
- {
- test01();
- system("pause");
- return 0;
- }
- //如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题
- #endif
|