c++中深浅拷贝构造区分

浅拷贝:

        概念:如果在类中没有自定义拷贝构造函数,那么使用编译器提供的拷贝构造函数(浅拷贝)

        影响:在调用浅拷贝构造函数时,两个对象会被分配到同一片空间;而每个对象结束时都会调用一次析构函数释放空间,当第一个对象结束时空间就已经被释放,第二个对象结束调用析构函数是就会出现错误,也就是二次释放问题

#include<iostream>
#include<cstring>
using namespace std;

class student
{
public:
    char * m_name;
    int m_age;


    student ()
    {
        cout << " have no arg " <<endl;
    }

    student (char * name,int age)
    {
        m_name=(char *)malloc(sizeof(name));
        if(m_name == NULL)
        {
            cout << " malloc is defoult " << endl; 
        }
        strcpy(m_name,name);
        cout << "have arg" << endl;
        if(age<O || arg >200)
        {
            cout << "age is defoult" << endl;
        }
        else
            m_age=age;
    }
    
    ~student()
    {
        if(m_name != NULL)
        {
            free(m_name);
             m_name = NULL;
        }
        cout << "析构函数" << endl;
    }
};
int main()
{
    student s1("jk",20);
    student s2(s1);
    return 0;
}

深拷贝:

        概念:在类中自定义拷贝构造函数,在调用时就会执行深拷贝构造,在自定义拷贝构造中申请空间,用来解决浅拷贝构造中内存二次释放的问题

#include<iostream>
#include<cstring>
using namespace std;

class student 
{
public:
    char * name;
    int age;

    student ()
    {
        cout << "have no arg" << endl;
    }
    student(char *name,int age)
    {
        strcpy(this->name,name);
        this->age=age;
    }

    student(const student &r_n)
    {
        name=(char *)malloc(sizefo(r_n.name));
        if(name == NULL)
        {
            cout << "malloc is degoult" << endl;
        }
        else 
            strcpy(name,r_n.name);
        
        if(r_n.age<0 || r_n.age>200)
            cout << "age is defoult" << endl;
        else
            age=r_n.age;
        cout << "have arg" << endl;
    }
    
    ~student()
    {    
        free(name);
        name=NULL;
        cout << "析构函数" << endl;
    }
};
int main()
{
    student s1("jk",20);
    student s2(s1);
    return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值