如何释放带有指针C++的容器

How to deallocate container with pointers C++

本文关键字:C++ 指针 何释放 释放      更新时间:2023-10-16

假设我有一个C类型的容器,其中有T*类型的指针。

C<T*> c;

如何在不使用辅助的情况下正确解除分配此容器类似的功能

template<class C>
void delete_all(C& c) {
    typename C::iterator next(c.begin()), last(c.end());
    while (next != last) {
        delete(*next);
        ++next;
    }
}

如果使用C++11,则可以使用C<std::unique_ptr<T>> c。在C++11之前,您可以尝试C<std::auto_ptr<T>>

如果您能够专门化C模板,那么将代码放入指针专门化的析构函数中。

template<> class C<T*> {
   //...
   C<T*>::~C () {
      // clean up
   }
}

但你们需要为你们的集装箱船的寿命担心一点。

如果你指的是STL容器,那么你不能这样做,但你可以使用一些智能指针类型来代替原始ptr,比如C++11中的boost::scope_ptr或std::unique_ptr。

此外,Boost指针容器可能会有所帮助:

http://www.boost.org/doc/libs/1_55_0/libs/ptr_container/doc/ptr_container.html