c++ - 了解 C++ 动态分配

标签 c++ dynamic allocation delete-operator

考虑以下代码:

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]) 中分配的内存。我不能在构造函数中执行此操作(我试过 delete[] p),因为它也是从主函数调用的,使用 char 数组作为参数,这些参数没有在堆上分配...如何我可以解决这个问题吗?

最佳答案

加法函数应该返回一个 CString,而不是一个 CString&。在加法函数中,您应该构建返回值,然后 delete[] 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++ - 了解 C++ 动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4647096/

相关文章:

c++ - 找出不同版本之间在 Boost 中所做的具体更改

将数组复制到动态分配的内存

memory - Go - 初始化一个空 slice

c++ - 为什么在这样的递归代码中避免内存分配/解除分配并不能节省运行时间?

c - 内存实际上是如何查找 C 数组的?

c++ - 从指向基对象的指针初始化派生对象

c++ - 为什么在单击编辑文本后不显示 qml 虚拟键盘,而我在 .pro 和 main.cpp 中调用插件

c++ - 如何分配连接的字符串?

c - 读取由命令选项和参数组成的输入,用空格分隔,在 C 中

validation - 发现意外的 Mach-O header 代码 : 0x72613c21 in Xcode 7