Cleaning up an STL list/vector of pointers

后端 未结 15 1295
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 21:41

What is the shortest chunk of C++ you can come up with to safely clean up a std::vector or std::list of pointers? (assuming you have to call delet

相关标签:
15条回答
  • 2020-11-28 22:30
    for (list<Foo*>::const_iterator i = foo_list.begin(), e = foo_list.end(); i != e; ++i)
        delete *i;
    foo_list.clear();
    
    0 讨论(0)
  • 2020-11-28 22:32

    The following hack deletes the pointers when your list goes out of scope using RAII or if you call list::clear().

    template <typename T>
    class Deleter {
    public:
      Deleter(T* pointer) : pointer_(pointer) { }
      Deleter(const Deleter& deleter) {
        Deleter* d = const_cast<Deleter*>(&deleter);
        pointer_ = d->pointer_;
        d->pointer_ = 0;
      }
      ~Deleter() { delete pointer_; }
      T* pointer_;
    };
    

    Example:

    std::list<Deleter<Foo> > foo_list;
    foo_list.push_back(new Foo());
    foo_list.clear();
    
    0 讨论(0)
  • 2020-11-28 22:32

    This seems cleanest imo, but your c++ version must support this type of iteration (I believe anything including or ahead of c++0x will work):

    for (Object *i : container) delete i;    
    container.clear();
    
    0 讨论(0)
  • 2020-11-28 22:33

    Actually, I believe the STD library provides a direct method of managing memory in the form of the allocator class

    You can extend the basic allocator's deallocate() method to automatically delete the members of any container.

    I /think/ this is the type of thing it's intended for.

    0 讨论(0)
  • 2020-11-28 22:33
    void remove(Foo* foo) { delete foo; }
    ....
    for_each( foo_list.begin(), foo_list.end(), remove );
    
    0 讨论(0)
  • 2020-11-28 22:37

    Since we are throwing down the gauntlet here... "Shortest chunk of C++"

    static bool deleteAll( Foo * theElement ) { delete theElement; return true; }
    
    foo_list . remove_if ( deleteAll );
    

    I think we can trust the folks who came up with STL to have efficient algorithms. Why reinvent the wheel?

    0 讨论(0)
提交回复
热议问题