垃圾回收如何处理这些由方法链接创建的静态实例

How is garbage collection handling these static instances created by method chaining

本文关键字:方法 链接 创建 实例 静态 何处理 处理      更新时间:2023-10-16

我想在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++中没有垃圾回收,需要清理内存,可以编写析构函数。

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

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

DoublyLinkedList* poly;

要知道,在C++中,您应该避免new,并在不需要的地方delete,并且更喜欢使用 RAII 语义。