C++方法返回自身副本时内存泄漏

C++ memory leak when method returns a copy of itself

本文关键字:内存 泄漏 副本 方法 返回 C++      更新时间:2023-10-16

我有一个类似于下面的 c++ 代码。这将在Base::add方法和total = &(*total + *to_add);中产生内存泄漏。我该如何解决这个问题?

#include <iostream>
#include <string>
class Base
{
    public:
        int n;
        Base(int input) : n(input) {}
        Base(const Base& input)
        {
            n = input.n;
        }
        Base& add(Base &other, bool new_obj=true)
        {
            Base *self;
            if (new_obj) {
                self = new Base(other);
            } else {
                self = this;
            }
            self->n += other.n;
            return *self;
        }
        Base& operator+=(Base &other)
        {
            return this->add(other, false);
        }
};
Base& operator+(Base &self, Base &other)
{
    return self.add(other);
}
class A : public Base
{
    using Base::Base;
    std::string print() {
        return "Class A method_a";
    }
};
class B : public Base
{
    using Base::Base;
    std::string print() {
        return "Class B method_b";
    }
};
int main()
{
    Base *total = new Base(0);
    for (int i=0; i<5; i++) {
        Base *to_add = new A(i);
        total = &(*total + *to_add);
    }
    for (int i=0; i<9; i++) {
        Base *to_add = new B(i);
        total = &(*total + *to_add);
    }
    return 0;
}

C++不是Java,你应该按值返回。从您的示例中不清楚派生类的用途,因此我假设您并不真正需要它们:

#include <iostream>
class Base
{
    public:
        int n;
        Base(int input) : n(input) {}
        Base(const Base& input) = default;
};
Base& operator+=(Base &x, const Base &y)
{
    x.n += y.n;
    return x;
}
Base operator+(const Base &x, const Base &y)
{
    return Base(x.n + y.n);
}
int main()
{
    Base total(0);
    for (int i=0; i<5; i++) {
        total += Base(i); // way 1
    }
    for (int i=0; i<9; i++) {
        total = total + Base(i); // way 2
    }
    return 0;
}
total = &(*total + *to_add);

你为什么要这样对自己?total = (total + to_add)不适合你吗?

在我看来,你好像试图在这里做矛盾的事情......

看起来你的 Base::add 函数是微不足道的,你可以按如下方式修改它:

        Base& add(Base &other)
    {
        n += other.n;
        return *this;
    }