In C + + deep copy and shallow copy problem is more important, a brief introduction to the meaning of deep copy and shallow copy, in C + + class by default There are six functions, copy constructor is included in the process of running the program, if there is no custom copy constructor, Then the program will use its own default constructor, which, in this process, is called a shallow copy, and the user-defined copy constructor is called a deep copy.
The main differences between deep and shallow copies are illustrated in the following practical examples:
#include <iostream>
#include <string>
using namespace Std;
Class A
{
Private
Char* _a;
Public
A (char* a=/* "" */null)
{
_a = new Char[strlen (a) + 1];
cout << "A ()" << Endl;
}
~a ()
{
if (_a! = NULL)
Delete _a;
_a = NULL;
cout << "~a ()" << Endl;
}
void Show ()
{
cout << _a << Endl;
}
};
int main ()
{
A ("123");
A AA (a);
GetChar ();
return 0;
}
This time the object a inside _a and the object AA in the _a share a space, this time when the program calls the destructor, the shared space will be released two times, the program will be problematic.
Deep copy, the user customizes a copy constructor itself, as shown in the following procedure
#include <iostream>
#include <string>
using namespace Std;
Class A
{
Private
Char* _a;
Public
A (char* a=/* "" */null)
{
_a = new Char[strlen (a) + 1];
cout << "A ()" << Endl;
}
~a ()
{
if (_a! = NULL)
Delete _a;
_a = NULL;
cout << "~a ()" << Endl;
}
A (const a &a)
{
_a = new Char[strlen (a._a) + 1];
strcpy (_a, a._a);
}
void Show ()
{
cout << _a << Endl;
}
};
int main ()
{
A ("123");
A AA (a);
cout << &a << Endl;
cout << &aa << Endl;
GetChar ();
return 0;
}
This article is from the "local and static Variables" blog, reproduced please contact the author!
Deep copy and shallow copy problems in C + +