How to deallocate object pointer in vector?

后端 未结 7 1399
野趣味
野趣味 2021-02-06 12:30

I have ;

class object {
                    // any private datas token in heap area 
             public : 
                   ~object () ; 

};
<
相关标签:
7条回答
  • 2021-02-06 13:29

    I wrote this generic function template, which should help you:

    template<typename FwdIterator>
    void deleter(FwdIterator from, FwdIterator to)
    {
       while ( from != to ) 
       {
           delete *from;
           from++;
       }
    }
    

    Example:

    struct object { ~object() { cout << "object deleted" << endl; } };
    
    int main() {
    
            vector<object*> objects;
            objects.push_back(new object());
            objects.push_back(new object());
            objects.push_back(new object());
            objects.push_back(new object());
            objects.push_back(new object());
    
            deleter(objects.begin(), objects.end()); //delete objects
            objects.clear(); //clear the vector
            return 0;
    }
    

    Output:

    object deleted
    object deleted
    object deleted
    object deleted
    object deleted
    

    Demo at ideone : http://www.ideone.com/t5PI0

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