【发布时间】: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),但我的没有,我想知道它是否可行。我用特定的约束写了这个,方法链接对我来说是一个实验;我现在看到确实调用了析构函数,这对我来说是最重要的问题。