本文是学习拷贝构造函数的一些总结,代码内容参考 https://www.cnblogs.com/alantu2018/p/8459250.html
1. 什么是拷贝构造函数
拷贝构造函数是一种特殊的构造函数,函数名与类的名字必须一致,必须有一个参数是本类型的引用变量。
普通类型的变量之间的复制很简单,例如:
int num = 1;
int count = num;
但是类的对象是非常复杂的,类对象之间的复制,需要调用类的拷贝构造函数进行:
#include<iostream>
using namespace std;
class CExample
{
private:
int a;
public:
//构造函数
CExample(int b)
{
a=b;
printf("constructor is called\n");
}
//拷贝构造函数
CExample(const CExample & c)
{
a=c.a;
printf("copy constructor is called\n");
}
//析构函数
~CExample()
{
cout<<"destructor is called\n";
}
void Show()
{
cout<<a<<endl;
}
};
int main()
{
CExample A(100);
CExample B=A;
B.Show();
return 0;
}
CExample实例化对象B复制对象A,调用Show()函数:
代码运行结果如下:
CExample(CExample & c)就是自定义的拷贝构造函数,内存给对象B分配了内存空间,对象B 复制了对象A。
2. 拷贝构造函数的调用时机
- 一个对象需要通过一个类对象初始化时
- 函数的输入参数为类对象
- 函数的返回值类型是类的对象
在以上三种情况中的第三种情况,本人在实际代码测试时,结果显示并没有调用拷贝构造函数,如下段代码所示:
#include<iostream>
using namespace std;
class CExample
{
private:
int a;
public:
//构造函数
CExample(int b)
{
a=b;
printf("constructor is called\n");
}
//拷贝构造函数
CExample(const CExample & c)
{
a=c.a;
printf("copy constructor is called\n");
}
//析构函数
~CExample()
{
cout<<"destructor is called\n";
}
void Show()
{
cout<<a<<endl;
}
};
CExample g_fun()
{
CExample temp(0);
return temp;
}
int main()
{
g_fun();
return 0;
}
运行结果如下:
而不是期望的
constructor is called
copy constructor is called
destructor is called
destructor is called
这是什么原因呢? 很多书上,以及网上的资料都显示,函数的返回值为类对象时,会调用拷贝构造函数,然而实际运行结果并非如此。原因是gcc做了优化,返回值为对象时,不再产生临时对象,因而不再调用复制构造函数。这种情况在VC++6.0中运行,就会显示调用拷贝构造函数了。如果想关闭这个优化,只需要在编译命令中加上“-fno-elide-constructors”参数,例g++ -fno-elide-constructors test.cpp 即可。
3. 关于深拷贝和浅拷贝
3.1浅拷贝
浅拷贝是拷贝对象的指针,拷贝出来的对象和原对象指向同一块内存,浅拷贝只会想类对象的成员变量简单的复制,编译器默认的拷贝构造函数能够完成这一功能,当类对象中含有静态变量,或者具有指针等动态成员时,浅拷贝不能使用,否则在析构时,析构函数会调用两次,产生野指针。
#include<iostream>
#include<assert.h>
using namespace std;
class Rect
{
public:
Rect()
{
p=new int(100);
}
~Rect()
{
assert(p!=NULL);
delete p;
}
private:
int width;
int height;
int *p;
};
int main()
{
Rect rect1;
Rect rect2(rect1);
return 0;
}
这段代码在运行之后会报错,原因在于声明rect2对象时,用默认拷贝构造函数,进行的是浅拷贝,只是将成员的值进行复制,rect2.p=rect1.p,使得rect2和rect1指向同一块地址如下图所示:
这样在析构的时候,会将同一块内存空间释放两次,出现错误。这种情况下,就需要用深拷贝,需要两个指针指向的两个不同的内存空间内有相同的值。
3.2 深拷贝
深拷贝在拷贝时,会另外开辟一段内存空间,拷贝对象的所有属性。
将上一段代码进行修改,自定义拷贝构造函数:
#include<iostream>
#include<assert.h>
using namespace std;
class Rect
{
public:
Rect()
{
p=new int(100);
}
Rect(Rect & r)
{
width = r.width;
height = r.height;
*p = *(r.p);
}
~Rect()
{
assert(p!=NULL);
delete p;
}
private:
int width;
int height;
int *p;
};
int main()
{
Rect rect1;
Rect rect2(rect1);
return 0;
}
这样,rect1和rect2的p 会各自开辟一段内存空间,但是指向的内存空间具有相同的值,这就是深拷贝。
一旦当类的数据成员中有指针变量时,在类的对象复制的时候,就必须要显示的声明拷贝构造函数,利用深拷贝去复制类的对象