Cleaning up an STL list/vector of pointers

后端 未结 15 1365
没有蜡笔的小新
没有蜡笔的小新 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:32

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

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

    Example:

    std::list > foo_list;
    foo_list.push_back(new Foo());
    foo_list.clear();
    

提交回复
热议问题