C++深拷贝和浅拷贝的区别

C++深拷贝和浅拷贝的区别

#include <iostream>
#include<cstring>

using namespace std;

class student {
public:
    student(const char* name, int age);//声明构造函数
    ~student();//析构函数

    //如果没有定义拷贝构造函数,编译器就自动生成默认拷贝构造函数:浅拷贝
   /* student(student& a)
    {
        this->name = a.name;
        this->age = age;
    }*/

    //自定义的拷贝构造函数:深拷贝
    student(student& a) {
        cout << __FUNCTION__ << endl;
        this->name = new char[256];

        this->age = a.age;
    }

private:
    char* name;
    int age;
};


student::student(const char* name, int age = 0)
{
    //定义构造函数
    cout << "//定义构造函数" << endl;
}

student::~student()
{
    //定义析构函数
    cout << "//定义析构函数" << endl;
    delete[]name;
}

int main()
{
    student myname("zhang",13);


 }



控制台结果:
image

什么时候需要自己定义拷贝构造函数?

当类数据成员中有指针成员的时候,需要申请内存空间。

深拷贝和浅拷贝的区别?

浅拷贝:只拷贝对象本身空间的内容,公用一个空间内存,

深拷贝:拷贝对象本身空间的内容,同时还分配指向的堆空间。

posted @ 2024-08-01 19:44  周半仙  阅读(20)  评论(0)    收藏  举报