其他分享
首页 > 其他分享> > 了解C动态分配

了解C动态分配

作者:互联网

请考虑以下代码:

class CString
{
private:
    char* buff;
    size_t len;

public:
    CString(const char* p):len(0), buff(nullptr)
    {
        cout << "Constructor called!"<<endl;
        if (p!=nullptr)
        {
            len= strlen(p);
            if (len>0)
            {
                buff= new char[len+1];
                strcpy_s(buff, len+1, p);               
            }           
        }       
    }

    CString (const CString& s)
    {
        cout << "Copy constructor called!"<<endl;
        len= s.len;
        buff= new char[len+1];
        strcpy_s(buff, len+1, s.buff);      
    }

    CString& operator = (const CString& rhs)
    {
        cout << "Assignment operator called!"<<endl;
        if (this != &rhs)
        {
            len= rhs.len;
            delete[] buff;          
            buff= new char[len+1];
            strcpy_s(buff, len+1, rhs.buff);
        }

        return *this;
    }

    CString operator + (const CString& rhs) const
    {
        cout << "Addition operator called!"<<endl;

        size_t lenght= len+rhs.len+1;
        char* tmp = new char[lenght];
        strcpy_s(tmp, lenght, buff);
        strcat_s(tmp, lenght, rhs.buff);

        return CString(tmp);
    }

    ~CString()
    {
        cout << "Destructor called!"<<endl;
        delete[] buff;
    }     
};

int main()
{
CString s1("Hello");
CString s2("World");
CString s3 = s1+s2;     
}

我的问题是我不知道如何删除在加法运算符函数中分配的内存(char * tmp = new char [length]).我无法在构造函数中执行此操作(我尝试删除[] p),因为它也是从main函数调用的,其中chars数组作为参数未在堆上分配…我怎样才能解决这个问题?

解决方法:

添加函数应返回CString,而不是CString&amp ;.在添加函数中,您应该构造返回值,然后删除不再需要的[] temp,因为在CString类中您可以创建内存副本.

CString operator + (const CString& rhs) const
{
    cout << "Addition operator called!"<<endl;

    size_t lenght= len+rhs.len+1;
    char* tmp = new char[lenght];
    strcpy_s(tmp, lenght, buff);
    strcat_s(tmp, lenght, rhs.buff);

    CString retval(tmp);
    delete[] tmp;
    return retval;
}

标签:c,dynamic,allocation,delete-operator
来源: https://codeday.me/bug/20190827/1737836.html