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); Parameters are references to objects of the same type, copy constructs 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 (Construction and destruction)
inlinestring::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 = ' + '; }} Inlinestring::~string () {
2.2 Class with pointer must have copy ctor (copy construction) and copy op (copy assignment)
Deep copy and shallow copy
Deep copy:
inlinestring::string (const string& str) { m_data = new Char[strlen (str.m_data) + 1]; Direct access to another object's private data //Can be UF meta-interpretation strcpy (m_data, str.m_data);}
Copy Assignment function:
Idea: If the right side is copied to the left, the steps are empty to the left, the same space is assigned to the right, and the copy is completed.
inlinestring& string::operator= (const string& str) { if (this = = &str) { //Detect self-assignment, not just efficiency issues return *this; If not tested, may cause the behavior undefined, see explanation } delete[] m_data; Clear left m_data = new char[strlen (str.m_data) + 1];//Open space strcpy (m_data, str.m_data);//Complete copy
Summary: A class with pointer variables, be sure to re-copy the construction, copy assignment and destructor!
C + + Class Design 2 (class with pointer members)