Tuesday, May 26, 2015

[LintCode] Assignment Operator Overloading (C++ Only)

Implement an assignment operator overloading method.
Make sure that:
  • The new data can be copied correctly
  • The old data can be deleted / free correctly.
  • We can assign like A = B = C

Example

If we assign like A = B, the data in A should be deleted, and A can have a copy of data from B. If we assign like A = B = C, both A and B should have a copy of data from C.

Challenge
Consider about the safety issue if you can and make sure you released the old data.

class Solution {
public:
    char *m_pData;
    Solution() {
        this->m_pData = NULL;
    }
    Solution(char *pData) {
        this->m_pData = pData;
    }

    // Implement an assignment operator
    Solution operator=(const Solution &object) {
        // write your code here
        if(this == &object) return *this;
        
        delete this->m_pData;
        this->m_pData = NULL;
        char *p = object.m_pData;
        if(!p) return *this;
        
        int len = 0;
        while(p && *p++) len++;
        
        this->m_pData = new char[len+1];
        this->m_pData[len] = 0;

        while(--len>=0) this->m_pData[len] = object.m_pData[len];
        
        return *this;
    }
};