How to deallocate object pointer in vector?

后端 未结 7 1376
野趣味
野趣味 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
    void deleter(FwdIterator from, FwdIterator to)
    {
       while ( from != to ) 
       {
           delete *from;
           from++;
       }
    }
    

    Example:

    struct object { ~object() { cout << "object deleted" << endl; } };
    
    int main() {
    
            vector 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

提交回复
热议问题