Coding Interviews 1

The first day. chapter 1&2 Open-mouthed smile

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 const CMyString&, from formal parameter to actual parameter the constructer will be invoked. Reference will not cause this kind of waste and increase the efficiency. const can help you not 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 are same, then return *this. If don’t make a judgment, you will release the memory of parameter too. You will not find the source of assignment.

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;
}

more advanced code

CMyString& CMyString::operator=(const CMyString& str)
{
    if (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 will be thrown out.

posted @ 2015-09-15 08:56  Bogart2015  阅读(129)  评论(0编辑  收藏  举报