看幕课网的笔记和自己的一些心得
浅拷贝;在拷贝构造函数中直接赋值的拷贝构造行为叫做浅拷贝,下面是一个简单的例子
#include<iostream>
using namespace std;
class student
{
public:
student(int i_age1){age = i_age1;}
student(const student & str){age = str.age;}
int getage(){return age;}
private:
int age;
};
int main()
{
student stu1(2);
student stu2(stu1);
cout << "stu1.age: " << stu1.getage() <<endl;
cout << "stu2.age: " << stu2.getage() <<endl;
return 0;
}
当类中含有指针的时候,通过构造函数,两个对象的指针变量就会指向同一片内存,当一个对象的指针变量修改内存中的值的时候,虽然另一个对象并没有修改其指向的内存的值,但是内存的值还是发生啦改变,这样就会发生类似计算机系统结构中读后写或者写后读类似的冲突,更严重的是如果其中一个销毁了指针变量,另一个对象的指针变量访问该段内存的时候会发生越界错误。为了避免这种情况的发生,于是出现了深拷贝,深拷贝是在拷贝构造函数中为新的对象(拷贝的发起者,暂称为对象2)申请一片和原来的对象(拷贝对象,暂称为对象1)大小相同的空间,这就需要拷贝构造函数有一个参数传进对象1指针参数的大小和指向的地址两个参数,因为对象2是新申请的空间,所以两个指针不指向同一片内存,对内存的操作也相互独立,在拷贝构造函数中对对象2赋值时需要使用循环一一赋值(值为对象1指向内存中一一对应的值)下面是我写的一个简单的浅拷贝会出错的例子,本来应该会出错的,但是不清楚为什么没出错,而且析构函数还执行了两遍,按道理来说是只执行一遍的,因为stu1执行析构函数之后stu2就没有内存可以析构了可能是我用的codeblocks编译器的缘故吧,日后再用vs尝试一下看是否会出错
#include<iostream>
using namespace std;
class student
{
public:
student(int i_age1){age = new int(i_age1);}
student(const student & str){age = str.age;cout<<"执行啦拷贝构造函数"<<endl;}
~student(){delete [] age;age = NULL;cout<<"析构函数"<<endl;}
int *getage(){return age;}
private:
int *age;
};
int main()
{
student stu1(2);
student stu2(stu1);
cout << "stu1.age: " << stu1.getage() <<endl;
cout << "stu2.age: " << stu2.getage() <<endl;
return 0;
}
由于浅拷贝在使用指针的时候出现的问题,我们必须要使用深拷贝,下面是代码
#include<iostream>
using namespace std;
class student
{
public:
student(int count)
{
mcount = count;
age = new int [mcount];
age[0] = a;
age[1] = b;
age[c] = c;
}
student(const student &str)
{
mcount = str.mcount;
age = new int [mcount];
for(int i = 0;i < mcount;i++)
{
age[i] = str.age[i];
}
cout << "拷贝构造函数"<<endl;
}
~student()
{
delete [] age;
age = NULL;
cout << "析构函数" <<endl;
}
/*void changex(student stu,int x)
{
stu.age[2] = x;
}*/
void printstu()
{
cout << "地址的值: "<< age <<endl;
cout << "值为:";
for(int i = 0; i < mcount;i++)
{
cout<< age[i] << " ";
}
cout << endl;
}
private:
int * age;
int mcount;
};
int main()
{
student stu1(5);
student stu2(stu1);
stu1.printstu();
stu2.printstu();
return 0;
}
由截图可以看到地址的值完全不同,这说明两个指针指向不同的地址,相互之间操作独立,ps因为我没有给这段内存赋值,因此这段内存中存放的是之前没有清除的值(可能是之前某个未知程序赋的值)