The first day. Chapter 1&2
Implement assignment function for below class cmystring.
class cmystring{public: cmystring (char* pData = NULL); CMyString (const cmystring& str); ~cmystring (void); Private : Char* m_pdata;};
Before coding I should focus on four points:
1 Whether The type of return value is the reference of CMyString, and returning the object itself (*this). If only return a reference, I can assign continuously like STR1=STR2=STR3. Otherwise, the codes cannot be compiled.
2 If The parameter is not a const cmystring& from formal parameter to actual parameter The Constructer would be invoked. Reference won't cause this kind of waste and increase the efficiency. Const can help you don't change the parameter for safety.
3 before get a new chunk of memory, I should release the existing memory first, in case of memory leak.
4 Make a judgment on whether the parameter is the same as (*this). If They is same, then return *this. If don ' t a judgment, you'll release the memory of parameter too. You'll not find the source of assignment.
cmystring& cmystring::operator= (const cmystring& str) { if ( this = = &str )return * this; Delete [] m_pdata; = NULL; New Char 1 ]; strcpy (M_pdata, str.m_pdata); return *this;}
More advanced Code
cmystring& cmystring::operator = ( Const Cmystring& str) { if ( Span style= "color: #0000ff;" >this = = &str) return *this ; else {cmystring tmp (str); char * ctmp = M_pdata; M_pdata = Tmp.m_pdata; Tmp.m_pdata = ctmp; return *this ;}
In this code, we consider about the problem on new. If the memory is not enough, then before we change the content of original object. The exception Bad_alloc is thrown out.
Coding Interviews 1