● 浅拷贝,简单的赋值拷贝操作。系统利用编译器提供的拷贝构造函数,会做浅拷贝操作。会造成堆区内存重复释放而导致程序崩溃,代码如下:

#include<iostream>

using namespace std;

class Person {
public:
    Person() {
        cout << "Person的默认构造函数调用" << endl;
    }

    Person(int age, int height) {
        m_Age = age;
        m_Height = new int(height);
        cout << "Person的有参构造函数调用" << endl;
    }

    ~Person() {
        if (m_Height != NULL) {
            delete m_Height;
            m_Height = nullptr;
        }
        cout<<"析构函数调用"<<endl;
    }

    int m_Age;
    int *m_Height;

};

void test() {
    Person p1(18,190);
    cout << "p1的年龄为: " << p1.m_Age << endl;
    cout << "p1的身高为: " << *p1->m_Height << endl;
    Person p2(p1);
    cout << "p2的年龄为: " << p2.m_Age << endl;
    cout << "p2的身高为: " << *p2.m_Height << endl;
}

int main() {
    test();
}

● 深拷贝,在堆区重新申请空间,进行拷贝操作。重新拷贝构造函数后,解决问题,代码如下:

#include<iostream>

using namespace std;

class Person {
public:
    Person() {
        cout << "Person的默认构造函数调用" << endl;
    }

    Person(int age, int height) {
        m_Age = age;
        m_Height = new int(height);
        cout << "Person的有参构造函数调用" << endl;
    }

    Person(Person &p){
        cout<<"Person拷贝构造函数调用"<<endl;
        m_Age = p.m_Age;
        m_Height = new int(*p.m_Height);
    }

    ~Person() {
        if (m_Height != NULL) {
            delete m_Height;
            m_Height = nullptr;
        }
        cout<<"析构函数调用"<<endl;
    }

    int m_Age;
    int *m_Height;

};

void test() {
    Person p1(18,190);
    cout << "p1的年龄为: " << p1.m_Age << endl;
    cout << "p1的身高为: " << *p1.m_Height << endl;
    Person p2(p1);
    cout << "p2的年龄为: " << p2.m_Age << endl;
    cout << "p2的身高为: " << *p2.m_Height << endl;
}

int main() {

    test();

}

注意:如果属性有在堆区开辟的,一定要提供拷贝构造函数,防止浅拷贝带来的问题。