Cleaning up an STL list/vector of pointers

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

    I'm not sure that the functor approach wins for brevity here.

    for( list::iterator i = foo_list.begin(); i != foo_list.end(); ++i )
        delete *i;
    

    I'd usually advise against this, though. Wrapping the pointers in smart pointers or using a specialist pointer container is, in general, going to be more robust. There are lots of ways that items can be removed from a list ( various flavours of erase, clear, destruction of the list, assignment via an iterator into the list, etc. ). Can you guarantee to catch them all?

提交回复
热议问题