简体   繁体   English

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

[英]How to deallocate container with pointers C++

Suppose I have a container of type C with pointers of type T*. 假设我有一个类型为C *且指针为T *的容器。

C<T*> c;

How can I properly deallocate this container without using auxiliary functions like 如何在不使用辅助功能的情况下正确地释放此容器

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

If you're using C++11, you could use C<std::unique_ptr<T>> c instead. 如果您使用的是C ++ 11,则可以改用C<std::unique_ptr<T>> c Pre-C++11 you could try C<std::auto_ptr<T>> . 在C ++ 11之前的版本中,您可以尝试C<std::auto_ptr<T>>

If you are able to specialize the C template then put your code in destructor of specialization for pointers. 如果您能够专用于C模板,则将代码放入指针的专用化析构函数中。

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

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

But then you need to worry about lifetime of your containters a bit. 但是随后您需要担心容器的寿命。

If you meant STL containers then you can't do this but you can use some smart pointer type instead of raw ptr - like boost::scoped_ptr or std::unique_ptr in C++11. 如果您的意思是STL容器,则不能这样做,但可以使用一些智能指针类型而不是原始的ptr-例如C ++ 11中的boost :: scoped_ptr或std :: unique_ptr。

Also Boost Pointer Containers might help: 另外,Boost Pointer Containers可能会有所帮助:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM