垃圾回收如何处理这些由方法链接创建的静态实例
How is garbage collection handling these static instances created by method chaining
我想在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 语义。
相关文章:
- 使用类模板的方法链接错误
- 为什么调用没有正文的纯虚拟方法不会导致链接器错误?
- 在使用库时,找到要链接的必要库的快速方法是什么
- 尝试使用 extern "C" 调用 C 中的C++方法,得到"undefined reference to"对象的链接器错误
- 将多个效果与 libSox 链接并读取输出数据的正确方法
- 当只有静态方法受到影响时,如何解决C++中的链接器错误?
- 从方法链接中使用的临时移动
- 使用 CMake 的静态方法链接错误
- 标准::字符串::空的未定义符号错误;Mac OS High Sierra 上的 c++ 标准方法链接错误
- 返回值上的 C++ 方法链接不起作用
- 方法链接中的C++执行顺序
- 将错误与静态方法链接
- 具有多态性 C++ 的方法链接
- 构造函数上的C++方法链接
- 重新加载了序列点和方法链接
- 来自命名空间的方法链接
- 方法链接导致编译错误
- 方法链接的缩进
- 垃圾回收如何处理这些由方法链接创建的静态实例
- 将内联非成员操作符的声明和定义分开的正确方法(链接器问题)