如何使用指针C ++释放容器

时间:2013-12-10 21:57:46

标签: c++ memory-management

假设我有一个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;
    }
}

2 个答案:

答案 0 :(得分:3)

如果您使用的是C ++ 11,则可以使用C<std::unique_ptr<T>> c代替。预C ++ 11你可以尝试C<std::auto_ptr<T>>

答案 1 :(得分:1)

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

template<> class C<T*> {
   //...

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

但是你需要担心一下你的包容器的生命周期。

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

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

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