gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:57:48 24 4
gpt4 key购买 nike

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

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

//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();

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

调用每个方法后,将创建一个新的(据我所知)“静态”声明的实例,并使用新实例调用更多方法。但是中间实例会发生什么?

最佳答案

C++中没有垃圾收集,需要清理内存,你可以写一个析构函数。

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

新建 的任何内容也必须删除 否则您将泄漏内存。此外,如果这是您创建 poly 成员变量的方式,它应该是类型

DoublyLinkedList* poly;

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

关于c++ - 垃圾回收如何处理这些由方法链创建的静态实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30899117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com