gpt4 book ai didi

c++ - 模板容器的析构函数

转载 作者:行者123 更新时间:2023-11-30 04:57:44 27 4
gpt4 key购买 nike

我正在用 C++ 构建一个类似 Java 的 ArrayList 类,只是为了练习(是的,我知道 std::vector 并且存在其他很棒的替代方案)。

据我所知,new关键字与 delete 配对关键字和 malloc, calloc, reallocfree 配对.

所以,假设我有一个类 ArrayList包含指向某些通用类型的指针 T .换句话说,我的 ArrayList 中的底层数组看起来像这样

T* array其中 T是一些template <typename T> .

我正在为 ArrayList 定义析构函数我有几个问题..

  1. 析构函数应该负责释放存储在ArrayList 中的所有内存。 .但我不知道 T* 是否它持有的是使用 new 创建的或 malloc -type,那么我该如何释放它们呢?我觉得遇到这个问题是反模式的标志,所以任何建议都将不胜感激!

  2. ArrayList本身可以通过两种方式实例化

在堆栈上...

ArrayList arr;

或者在堆上...

ArrayList arr = new ArrayList();

如果它是在堆栈上初始化的,我就不用担心管理 arr的内存,但我可以假设它的析构函数将在 arr 之前被调用吗?本身以某种方式被释放?

如果它是在堆上初始化的,调用delete arr调用它的析构函数释放arr本身?

谢谢!

最佳答案

The deconstructor should be responsible for freeing all the memory stored in the ArrayList. But I don't know if the T*s that it's holding were created using a new or a malloc-type, so how do I dealloc them? I feel like running into this problem is a sign of an anti-pattern, so any advice would be appreciated!

你不应该接受任何T*。您是正确的,您无法确定应如何释放此类指针。您应该自己处理分配(如 std::vector 所做的那样),在这种情况下您不再有这个问题。

If it was initialized on the stack, I don't have to worry about managing arr's memory, but can I assume that its deconstructor will be called before the arr itself is somehow deallocated?

是的。当局部变量超出范围时,对象(如果有)将被销毁。这涉及调用其析构函数(再次调用,如果有的话)。

If it was initialized on the heap, does calling delete arr call its deconstructor and deallocate arr itself?

是的。 delete arr 调用 arr 的析构函数(同样,如果有的话)并释放保留的内存。

关于c++ - 模板容器的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51972237/

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