我有一个类似于下面的C++代码。这会给Base::add
方法和total = &(*total + *to_add);
带来内存泄漏。我该如何解决?当方法返回自己的副本时C++内存泄漏
#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;
}
为了能够回答你需要解释你想要完成的事情。这将给出关于新创建的对象的所有权的想法。他们应该成为孩子吗? – user2672165
按值而不是指针返回。 – PcAF
'self = new Base(other);'你永远不会打电话给'delete'。 –