具有数字集C++的多态性中的内存泄漏

Memory leak in polymorphism with number sets C++

本文关键字:多态性 内存 泄漏 C++ 数字      更新时间:2023-10-16

我现在正在学习C++多态性,老师希望我们使用基类number_t和派生类:integer_treal_t

如果没有多态性,我会植入与以下非常相似的operator+

real_t real_t::operator+(const integer_t& number) const
{
    /* Sum operations of (real_t + integer_t) */
    /* Create a new real with the result of the sum and return it */
    return real_t(...); 
}

这样,当有两个数字的和时,它不会改变所涉及的数字的值,而是返回一个新的值。

但是对于多态性,我必须返回一个指针,例如,这就是我要做的:

number_t* real_t::operator+(const number_t* number) const
{
    /* Sum operations of two numbers which will output a real_t (for example)*/
    /* Create a new real with the result of the sum and return it */
    /* The return value will be of the type of the biggest set, for example: 
         integer + real = real
         complex + real = complex
    */
    return new real_t(...); 
}

这里的问题是new运算符创建的内存不会被释放。在此操作中:

d = (a + b) + c

由总和(a+b)分配的内存永远不会被释放。

有什么更好的方法吗?

返回智能指针:

unique_ptr<number_t> real_t::operator+(const number_t& number) const
{
    /* Sum operations of two numbers which will output a real_t (for example)*/
    /* Create a new real with the result of the sum and return it */
    return make_unique<real_t>(...); 
}

现在,中间值将自动释放。