关于C ++中的自定义对象的构造函数/析构函数和新的/删除操作符 [英] About constructors/destructors and new/delete operators in C++ for custom objects

查看:126
本文介绍了关于C ++中的自定义对象的构造函数/析构函数和新的/删除操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个我自己创建的链接列表。它有自己的析构函数,释放内存。此链接列表不会重载新的或删除。

Suppose I have a Linked List I created myself. It has its own destructor, which frees the memory. This Linked List does not overload new or delete.

现在,我试图创建一个所述链表的数组(打开散列,如果我理解正确)。然后我在这个打开哈希类的构造函数中分配必要的内存。在构造函数内部调用的新操作符足以正确分配数组的内存,对吗?我不确定,因为我没有重载的新的Linked List类。

Now, I'm trying to create an array of said linked lists (open hashing, if I understand correctly). Then I allocate the necessary memory inside the constructor of this open hashing class. The new operator being called inside the constructor is enough to correctly allocate the memory for the array, right? I'm not sure because I haven't overloaded new for the Linked List class.

此外,假设我的链表的数组被称为元素,我可以写删除[]元素在析构函数中?是否会为数组中的每个元素调用析构函数并正确释放内存?

Also, assuming my array of Linked Lists is called elements, could I just write "delete[] elements" in the destructor? Would that call the destructor for each element in the array and correctly free the memory?

最后,如果我的假设都是正确的(即,我不必重载

Finally, if both my assumptions are correct (ie, I don't have to overload new and delete to use them with my custom class), what is the point of overloading such operators?

推荐答案

是的,你是正确的。一个普通的

Yeah you are right. A plain

elements = new LinkedList[N];

足以分配它们。

elements[i]->push(....);

并使用显示的方式在析构函数中删除它们:

and delete them in your destructor using the way you showed:

delete[] elements;

编译器将记住分配了多少个元素,并为每个列表正确调用析构函数。重载new和delete操作符的重点是提供自定义内存分配策略。例如,您可以预分配内存,然后从该池中取出,而不是再次从操作系统分配内存。

The compiler will remember how many elements were allocated, and call the destructor for each list correctly. The point of overloading the new and delete operator is to provide custom memory allocation strategy. For example, you could preallocate memory, and then take from that pool, instead of allocating everytime again memory from the OS.

但是,您必须编写一个复制构造函数和复制分配运算符。因为如果有人复制你的哈希映射,链表必须被复制,而不仅仅是指针。或者你可以使复制构造函数和复制赋值运算符是私有的,不要定义它们,不允许你的散列映射的副本:

But note, you have to write a copy constructor and copy assignment operator too. Since if someone copies your hash map, the linked list has to be copied too, and not just the pointer. Or you can make the copy constructor and copy assignment operator private and don't define them, disallowing copies of your hash map:

....
private:
    MyHashMap(MyHashMap const& rhs);
    MyHashMap & operator=(MyHashMap const& rhs);
....

这篇关于关于C ++中的自定义对象的构造函数/析构函数和新的/删除操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆