Two class with pointer members (class String)
1. Test code (use effect)
int main ()
{
string S1 (),
string s2 ("Hello"); Constructor
String S3 (S1); Copy construction
cout << S3 << Endl;
s3 = S2; Copy Assignment
cout << S3 << Endl;
}
2 Big Three (three kinds of special functions)
Class String
{public
:
String (const char* CSTR = 0);
String (const string& str); parameter is a reference to the same type of object, the copy construct
string& operator= (const string& str);//Copy Assignment
~string ()/destructor
char* Get_c _str () const{return
m_data;
}
Private:
char* m_data;
2.1 ctor & Dtor (structure and destructor)
Inline
string::string (const char* CSTR = 0)
{
if (CStr) {
m_data = new Char[strlen (CStr) +1];
strcpy (M_DATA,CSTR);
}
else{ //Unspecified length
m_data = new char[1];
*m_data = ' n ';
}
}
Inline
string::~string ()
{
delete[] m_data;
The 2.2 Class with the pointer members must have copy ctor (copy construction) and copy op (copy assignment)
Deep copy and shallow copy
Deep copy:
Inline
string::string (const string& str) {
m_data = new Char[strlen (str.m_data) + 1]; Direct access to the private data of another object
//can be interpreted
strcpy (m_data, str.m_data);
}
Copy Assignment function:
Train of thought: if the right copy to the left, the step is to clear the left, allocate the same space as the right, complete the copy.
Inline
string& string::operator= (const string& str) {
if (this = = &str) { //Detect self assignment, not just efficiency issues return
*this; If not, the behavior may not be defined, see the following figure explained
}
delete[] m_data; Clear left
m_data = new char[strlen (str.m_data) + 1];//Open space
strcpy (m_data, str.m_data);//Complete copy return
*this
Summary: Classes with pointer variables must be copied, copied, assigned, and destructors.