What do I need to do before deleting elements in a vector of pointers to dynamically allocated objects?

后端 未结 5 780
天涯浪人
天涯浪人 2020-11-30 06:35

I have a vector that I fill with pointers to objects. I am trying to learn good memory management, and have a few general questions:

  1. Is it true that when I am
5条回答
  •  生来不讨喜
    2020-11-30 07:26

    Is it true that when I am done with the vector I must loop through it and call delete on each pointer?

    Well, you don't have to loop by hand, you can also use an algorithm:

    #include 
    #include 
    #include 
    
    int main()
    {
        std::vector vec;
        vec.push_back(new Derived());
        vec.push_back(new Derived());
        vec.push_back(new Derived());
    
        // ...
    
        std::for_each(vec.begin(), vec.end(), std::default_delete());
    }
    

    If you don't have a C++0x compiler, you can use boost:

    #include 
    #include 
    
    std::for_each(vec.begin(), vec.end(), boost::lambda::delete_ptr());
    

    Or you can write your own functor:

    struct delete_ptr
    {
        template 
        void operator()(T* p)
        {
            delete p;
        }
    };
    
    std::for_each(vec.begin(), vec.end(), delete_ptr());
    

提交回复
热议问题