浅拷贝:
概念:如果在类中没有自定义拷贝构造函数,那么使用编译器提供的拷贝构造函数(浅拷贝)
影响:在调用浅拷贝构造函数时,两个对象会被分配到同一片空间;而每个对象结束时都会调用一次析构函数释放空间,当第一个对象结束时空间就已经被释放,第二个对象结束调用析构函数是就会出现错误,也就是二次释放问题
#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;
}