DeepCopy.cpp
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Person
{
private:
static int Count;
char* Country;
char* Name;
int Age;
public:
Person();
Person(Person& P);
void set(char* country, char* name, int age);
void show();
~Person();
};
int Person::Count = 0;
Person::Person()
{
Count++;
cout << "constructor is called.............." << endl;
}
Person::Person(Person& P)
{
cout << "copy constructor is called................." << endl;
Count++;
Age = P.Age;
Country = new char[strlen(P.Country)+1];
Name = new char[strlen(P.Name)+1];
strcpy(Country, P.Country);
strcpy(Name, P.Name);
}
void Person::set(char* country, char* name, int age)
{
Country = country;
Name = name;
Age = age;
}
void Person::show()
{
cout << "Name: " << Name << endl;
cout << "Country: " << Country << endl;
cout << "Age: " << Age << endl;
cout << "Count: " << Count << endl;
}
Person::~Person()
{
cout << "destructor is called...............\n";
Count--;
}
int main()
{
char* name;
name = "Renne";
char* country;
country = "China";
Person Renne;
Renne.set(country, name, 20);
Renne.show();
Person copy(Renne);
copy.show();
return 0;
}
如果不自己定义拷贝构造函数的话,系统会在拷贝的时候调用默认拷贝构造函数,但是默认拷贝构造函数进行的是浅拷贝!即只复制成员的值,当类的成员中含有指针的时候,这两个类的实例的指针指向同一块内存,当程序运行完毕调用析构函数的时候就会对同一块内存地址释放两次,会出现double free重析构错误。
所以当类中含有指针时,必须要深拷贝。
此外,默认拷贝函数不会对静态成员变量进行操作。