1.深拷贝和浅拷贝
C++在三种情况下会调用拷贝构造函数(可能有纰漏),第一种情况是函数形实结合时,第二种情况是函数返回时,函数栈区的对象会复制一份到函数的返回去,第三种情况是用一个对象初始化另一个对象时也会调用拷贝构造函数。
下面是浅拷贝
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <vector>
using namespace std;
class Str{
public:
char *value;
Str(char s[])
{
cout<<"调用构造函数..."<<endl;
int len = strlen(s);
value = new char[len + 1];
memset(value,0,len + 1);
strcpy(value,s);
}
Str(Str &v)
{
cout<<"调用拷贝构造函数..."<<endl;
this->value = v.value;
}
~Str()
{
cout<<"调用析构函数..."<<endl;
if(value != NULL)
delete[] value;
}
};
int main()
{
char s[] = "I love BIT";
Str *a = new Str(s);
Str *b = new Str(*a);
delete a;
cout<<"b对象中的字符串为:"<<b->value<<endl;
delete b;
return 0;
}
把指针指向同一块内存 ,这样的危险在于一旦释放内存 同一块内存被释放两次 会程序崩溃
所以copy 构造要避免浅拷贝
下面是深拷贝
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <vector>
using namespace std;
class Str{
public:
char *value;
Str(char s[])
{
cout<<"调用构造函数..."<<endl;
int len = strlen(s);
value = new char[len + 1];
memset(value,0,len + 1);
strcpy(value,s);
}
Str(Str &v)
{
cout<<"调用拷贝构造函数..."<<endl;
int len = strlen(v.value);
value = new char[len + 1];
<