为什么我们需要在C ++赋值运算符中删除分配的内存? [英] Why do we need to delete allocated memory in C++ assignment operator?

查看:235
本文介绍了为什么我们需要在C ++赋值运算符中删除分配的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们需要delete语句?

Why do we need the delete statement?

const MyString& operator=(const MyString& rhs)
{ 
    if (this != &rhs) {
        delete[] this->str; // Why is this required?
        this->str = new char[strlen(rhs.str) + 1]; // allocate new memory
        strcpy(this->str, rhs.str); // copy characters
        this->length = rhs.length; // copy length
    }
    return *this; // return self-reference so cascaded assignment works
}


推荐答案

这不是一个复制构造函数,它是赋值运算符。你需要被删除,因为被分配的对象保持已经是一个以前的值。

This is not a copy constructor, it's the assignment operator. You need the deleted because the object being assigned is holding already a previous value.

这个代码也不是很好,因为首先删除旧的值,然后分配新的...但是分配可能会抛出异常,在这种情况下,对象将保留一个指向解除分配区域的指针。一个更好的方法是首先分配然后删除旧的值(一个异常不应该允许从析构函数... 请参阅此链接以获取解释),因此分配成功或失败,不会影响任何内容。

This code is also not really good because first deletes the old value and then allocates the new one... but the allocation may throw an exception and in this case the object will keep a pointer to a deallocated area. A better approach is first allocate and then delete the old value (an exception should never be allowed to escape from a destructor... see this link for an explanation) so either the assignment succeeds or fails without compromising anything.

一个常见的习语是实现一个复制构造函数和一个交换操作(交换两个实例的内容,保证没有异常被抛出)。然后,您实施指定运算符合并两个 ...这需要从异常处理的角度来看,这两个代码都很少,并且是鲁棒的。

A common idiom is to implement a copy constructor and a swap operation (that swaps the contents of two instances guaranteeing that no exception will be thrown). Then you implement the assignment operator combining the two... this requires both less code and is robust from an exception handling point of view.

这篇关于为什么我们需要在C ++赋值运算符中删除分配的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆