首页 > 其他 > 详细

Coding Interviews 1

时间:2015-09-15 09:18:12      阅读:276      评论:0      收藏:0      [点我收藏+]

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 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.

Coding Interviews 1

原文:http://www.cnblogs.com/Bogart/p/4809195.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!