1.C++类的深拷贝与浅拷贝


# C++类的深拷贝与浅拷贝

堆区的内存重复释放


改进,拷贝构造都开辟新的内存

```

#include


using namespace std;


class Person

{

    public:

    Person()

    {

        cout << "Person默认构造函数调用" << endl;

    }

    Person(int age, int height)

    {

        cout << "Person有参构造函数调用" << endl;

        m_Age = age;

        m_Height = new int(height);

    }

Person(const Person & p)

{

        cout << "Person拷贝构造函数调用" << endl;

        //m_Height = p.m_Height; 编译器默认实现这个代码

        //深拷贝操作

        m_Height = new int(*p.m_Height);//*p.m_Height 解引用,得到参数存储的内存地址

    }

//浅拷贝带来堆区的重复释放

~Person()

{ //析构代码, 将堆区开辟数据做释放操作

    if (m_Height != NULL)

{

delete m_Height;

//放置野指针的出现,先置空

m_Height = NULL;

}

    cout << "Person析构函数调用" << endl;

}

    int m_Age;

    int *m_Height; //身高

};

void test01()

{

    Person p1(18, 160);

    cout << "p1的年龄为: " << p1.m_Age << "身高为: " << *p1.m_Height << endl;

    Person p2(p1);

    cout << "p2的年龄为: " << p1.m_Age << "2身高为: " << *p1.m_Height << endl;

}

int main()

{

    test01();

    system("pause");

    return 0;

}

```

你可能感兴趣的:(1.C++类的深拷贝与浅拷贝)