【问题标题】:How is garbage collection handling these static instances created by method chaining垃圾收集如何处理这些由方法链创建的静态实例
【发布时间】:2015-06-17 18:07:30
【问题描述】:

我想在 C++ 中使用方法链接,但我担心内存泄漏——我不知道垃圾收集是如何处理方法调用返回的中间实例的。

请注意,我故意不返回(这个),因为这是程序的要求。

//important to note that in the constructor of Polynomial, I allocate a new 

DoublyLinkedList instance as a private member
class Polynomial {
    private:
    DoublyLinkedList * poly;
    //other stuff, constructors and destructor
};

//this is the primary constructor I am using. Notice that I allocated one of its members in the heap
Polynomial::Polynomial(int array [], int size) {
    poly = new DoublyLinkedList;
    //fill in with the array and size etc.
}

Polynomial::~Polynomial() {
    //deallocate the allocated members
}

//------ ADD --------
Polynomial Polynomial::add(Polynomial* polyB){  //does addition by default
    //perform add operations and save results into an array called "result" for passing into a Polynomial constructor

    return Polynomial(result, maxSize); //will return a NEW instance
}
//example prototypes which return a Polynomial instance (not a pointer to a new instance)
Polynomial Polynomial::add(Polynomial * polyB);
Polynomial Polynomial::subtract(Polynomial * polyB);
Polynomial Polynomial::multiply(Polynomial * polyB);

DoublyLinkedList::DataType polyArrayA [] = {1,3,4};
DoublyLinkedList::DataType polyArrayB [] = {5, 5, 7};
Polynomial p1 = Polynomial(polyArrayA, 3);
Polynomial p2 = Polynomial(polyArrayB, 3);

Polynomial p3 = p1.add(&p1).multiply(&p1).subtract(&p2);

p3.print();

知道垃圾收集处理静态声明的变量后,我决定这些方法可以返回“多项式”而不是返回指针。问题是多项式是一个新实例化的实例(在方法中创建)并且它有一个动态分配的成员——所以我需要确保它的解构函数被调用。

在调用每个方法后,会创建一个新的(AFAIK)“静态”声明的实例,并使用新实例调用其他方法。但是中间实例会发生什么?

【问题讨论】:

  • 不太确定您不将其作为程序要求返回是什么意思;这就是这样做的方法。但是,您应该知道这在 C++ 中是非常不习惯的。方法链接通常返回一个引用 (*this)。如果要返回一个新实例,出于各种原因,通常最好编写一个不是成员的函数 add 或 operator+。此外,“静态”一词并不意味着您认为它在 C++ 中的作用。
  • 没错,因为方法链接通常返回 (*this),但我的没有,我想知道它是否可行。我用特定的约束写了这个,方法链接对我来说是一个实验;我现在看到确实调用了析构函数,这对我来说是最重要的问题。

标签: c++ garbage-collection


【解决方案1】:

C++没有垃圾回收,需要清理内存,可以写析构函数。

Polynomial::~Polynomial() {
    delete poly;
}

new 的任何东西都必须delete 否则你正在泄漏内存。此外,如果这是您创建 poly 成员变量的方式,它应该是类型

DoublyLinkedList* poly;

知道在 C++ 中,您应该避免在不需要的地方使用 newdelete,而更喜欢使用 RAII semantics

【讨论】:

  • 是的,谢谢——那是一个错字。我确实写了一个析构函数,但我主要担心的是我不确定它是否被调用。我将包含一个 add 函数的示例,以便您获得更好的图片。另外,也许垃圾收集不是正确的术语?我认为这就是您描述程序在离开范围后如何自动摆脱静态变量的方式。
猜你喜欢
  • 2015-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
相关资源
最近更新 更多