When an interviewer asks a candidate to overload the assignment operator, he or she asks the following
questions to check the candidate's code:
-
Does it return a reference? Before the assignment operator function ends, it should
return the instance itself (*this) as a reference. If an assignment operator is
overloaded as a void function, it has no chance to chain multiple assignments
together. Suppose that there are three instances of the CMyString type: str1, str2,
and str3. They cause a compiling error at str1=str2=str3 if the assignment
operator is overloaded as a void function.
-
Is the argument passed by a constant reference? If the argument is passed by value,
a copy constructor is called, and it is a waste of time. The call of the copy
constructor is avoided if the argument is passed by reference. Additionally, it should
not modify the status of the input instance during assignment, so the reference
should be declared as const.
-
Is the existing memory freed? If the old memory for m_pData is not deallocated
before it allocates new memory, memory leaks occur.
-
Does it protect against self-assignment? It returns directly and does nothing if the
assignment source (input instance) is identical to the assignment target (*this).
Otherwise if *this is the same as the input instance, its memory will be freed and its
content cannot be gotten back anymore.
Listing 2-10 is a piece of C++ code, covering all four items.
Listing 2-10. C++ Code for Assignment Operator (Version 1)
CMyString& CMyString::operator =(const CMyString &str) { if(this == &str)
return *this;
delete []m_pData; m_pData = NULL;
m_pData = new char[strlen(str.m_pData) + 1]; strcpy(m_pData, str.m_pData);
return *this; }
This is a classic solution in textbooks. A junior candidate can pass this round of interview with the code above. However, it is far from perfection. An interviewer will have more stringent requirements if the candidate is a senior C++ programmer.
No comments:
Post a Comment