2016-06-14 28 views
-1

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

为了能够回答你需要解释你想要完成的事情。这将给出关于新创建的对象的所有权的想法。他们应该成为孩子吗? – user2672165

+1

按值而不是指针返回。 – PcAF

+1

'self = new Base(other);'你永远不会打电话给'delete'。 –

回答

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

如何返回新的C +用'operator +'+11右值引用? – Aconcagua

+0

@Aconcagua:它是如何改变的?如果它被动态分配,谁将负责删除它? – ybungalobill

+0

我不想回头看看动态分配:'Base && operator +(/*...*/){return Base(x.n + y.n); }'。对我来说,允许移动语义似乎是一个好主意,我想问你的意见,所以问号实际上是一个真正的问号... – Aconcagua

0
total = &(*total + *to_add); 

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

因为如果你想在这里做的东西矛盾在我看来,...

0

看来你的基地::新增功能是微不足道的,你可以按如下修改:

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