aah134
aah134

Reputation: 860

deleting vector or pointers compiler error

I have the following function, used to work properly, however, I don't know what I did, I started to get some strange error

Container is a vector of pointers

template<typename Container>
void delete_collections(Container& c) 
{ 
    while(!c.empty()) 
    {
        delete c.back(); //<=== here
        c.back() = NULL;
        c.pop_back();    //<=== & here
    }
}

first error

**Multiple markers at this line

second errro

solution I passed a map to the function by mistake once, I wish compiler gave any warning though.

Upvotes: 1

Views: 96

Answers (1)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

Just for the record, I would use a specialized container instead, take a look at e.g. Boost. Alternatively, store smart pointers where you don't have to call delete manually. Still, here's how to do it in a way that works with every container except maps:

template<typename container>
void delete_all(container& c) {
    for(typename container::const_iterator it=c.begin(), end=c.end(); it!=end; ++it)
        delete *it;
    c.clear();
}

With C++11, you could use auto, too, instead of typename container::const_iterator.

Upvotes: 2

Related Questions