如何处理模板类中的指针? [英] How to deal with pointers in template classes?
问题描述
当考虑像BinaryTree这样的模板化数据结构时,处理指针类型的最简洁的方法是什么?
When considering a templated data strucuture like a BinaryTree, what is the cleanest way to deal with pointer types?
如果树保存指针,它们必须在删除子树时返回到堆。但是我怎么能从BinaryTree类里面告诉它,它是由malloc或新分配的?
If the tree holds pointers, the memory pointed to by them must be returned to the heap on deletion of sub-trees. But how can I tell from inside the BinaryTree class, wether it was allocated by malloc or new?
一个解决方案是设置标志,指示存储的数据类型。但是我的类将依赖于外部的正确使用...
One solution would be to set flags, indicating the type of data stored. But than my class would rely on correct usage from outside...
另一个想法是传递一些向量到所有可能删除子树的BinaryTree方法。每当一个子树被删除,它将存储的数据添加到向量,最后我可以从BinaryTree之外正确处理它们。
Another idea was passing some kind of vector to all the BinaryTree methods that might delete a sub-tree. Whenever a sub-tree is deleted, it adds the stored data to the vector and in the end I can handle them correctly from outside the BinaryTree.
但这听起来像一个
推荐答案
将原始指针存储在像BinaryTree这样的容器中的唯一原因是如果您要在其他位置存储/管理引用对象。在这种情况下,简单地删除指针(而不是它们指向的对象)就足够了,因为对象的删除是在别处处理的。
The only reason for storing raw pointers in a container like BinaryTree is if you want to reference objects stored/managed elsewhere. In that case, simply deleting the pointers (not the objects pointed to by them) is enough, because the deletion of the objects is handled elsewhere.
如果您想在树中管理动态分配的对象,请使用例如 std :: unique_pointer< T>
作为容器的元素类型。在这种情况下,再次简单地删除存储的元素将会做,因为删除 std :: unique_pointer
意味着删除它指向的对象。
If you want to manage dynamically allocated objects in your tree, use e.g. std::unique_pointer<T>
as the element type of the container. In that case, again simply deleting the stored element will do, because deleting the std::unique_pointer<T>
implies deleting the object pointed to by it.
这篇关于如何处理模板类中的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!