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

时间:2016-06-14 06:50:58

标签: c++ memory-leaks

我有一个类似于下面的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;
}

3 个答案:

答案 0 :(得分:1)

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;
}

答案 1 :(得分:0)

total = &(*total + *to_add);

你为什么要对自己这样做? 没有total = (total + to_add)为你工作吗?

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

答案 2 :(得分:0)

看起来您的Base :: add函数很简单,您可以按如下方式修改它:

{{1}}