我有很多代码,我在删除在其中有指针的向量容器,也就是说,我必须首先删除所有的指针,然后清除容器.每次我会遍历并手动删除指针(我知道stl ::
algorithms for_each).为了规避所有的代码,我创建了一个模板,用于删除所有具有指针的向量容器.到现在为止还挺好.
现在我有几个容器类型,包括地图,并发容器等,到目前为止,所有功能都有相同的功能,只要删除.我拥有的DeleteContainer(std :: vector< T *& VecIn)函数只能在上面提到的向量上工作.有没有什么办法使其通用到足以在所有容器上工作?
EDIT: Thanks for all the answers,I wish I could select more than one. To anybody who stumbles onto this question,read all the answers and not just the selected one as they all provide great info.
解决方法
你已经有了一个有效的答案,只是为了提供一个替代方案,我相信你应该考虑使用
Boost Pointer Container,让它处理内存管理:
This library therefore provides
standard-like containers that are for
storing heap-allocated or cloned
objects (or in case of a map,the
mapped object must be a heap-allocated
or cloned object). For each of the standard containers there is a pointer container equivalent that takes ownership of the objects in an exception safe manner.