Cleaning up an STL list/vector of pointers

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

    It's really dangerous to rely on code outside of the container to delete your pointers. What happens when the container is destroyed due to a thrown exception, for example?

    I know you said you don't like boost, but please consider the boost pointer containers.

    0 讨论(0)
  • 2020-11-28 22:41
    for(list<Foo*>::const_iterator it = foo_list.begin(); it != foo_list.end(); it++)
    {
        delete *it;
    } 
    foo_list.clear();
    

    There's a small reason why you would not want to do this - you're effectively iterating over the list twice.

    std::list<>::clear is linear in complexity; it removes and destroys one element at a time within a loop.

    Taking the above into consideration the simplest to read solution in my opinion is:

    while(!foo_list.empty())
    {
        delete foo_list.front();
        foo_list.pop_front();
    }
    
    0 讨论(0)
  • 2020-11-28 22:43

    If you allow C++11, you can do a very short version of Douglas Leeder's answer:

    for(auto &it:foo_list) delete it; foo_list.clear();
    
    0 讨论(0)
提交回复
热议问题