1

Suppose I have a vector as such

std::vector<float*> vec;

Now I know that I need to delete the pointers inside the vector to reclaim memory. The way I know is by iterating through the vector and deleting each pointer. I wanted to know if there was a faster way of accomplishing this.

I have the following scenario

std::vector<float*> cont;

for(int i=0; i < SelectedColumns.size();i++)
{
    if(someList.count()>0)
    {
        float *a = new float(  column_cell_mapper[SelectedColumns[i]]->text().toFloat());
        cont.push_back(a);
        someclass.somemethod(*a) // Requires a reference
        ....
        ....
    }       
}
someclass.process();
MistyD
  • 16,373
  • 40
  • 138
  • 240

2 Answers2

3

Use std::unique_ptr. When your vector goes out of scope, each float will be destructed with no extra work from you.

std::vector<std::unique_ptr<float>> vec

If you really just want a container for a arrays of float, see Mark B's answer and use std::vector<std::vector<float>> instead.

Community
  • 1
  • 1
  • The unique ptr would be allocated under a loop and would go out of scope so this doe snot work for me. – MistyD Sep 19 '13 at 15:12
  • Is there any reason you can't do `vec.emplace_back(new float{...})` –  Sep 19 '13 at 15:14
  • 1
    @justinls That code can leak; you should use `push_back` for smart pointers. `emplace_back` might need to reallocate which can throw an exception, and if it does then the memory will be leaked before it can ever become owned by a smart pointer. – Simple Sep 19 '13 at 15:40
  • +1, thanks for the correction. I'll be happier when we get a `std::make_unique`! –  Sep 19 '13 at 17:26
3

EDIT:

Can you get away with reversing the order of function call vs insert to vector? For example can you do this?

    float a = column_cell_mapper[SelectedColumns[i]]->text().toFloat();
    someclass.somemethod(a) // Requires a reference
    cont.push_back(a);

Original answer:

Just don't store the floats by pointer and use std::vector<float> instead. For small simple types like float using the extra level of indirection doesn't buy you anything. If you really really really need to store individual floats by pointer, you can use std::unique_ptr with C++11 or boost::shared_ptr with previous C++ versions.

Now, if your float* is pointing to an array of floats, still don't do it that way. Instead use a vector of vectors thusly:

std::vector<std::vector<float> > vec;

This will still automatically clean up the memory for you and enable you to concentrate on writing correct algorithms rather than spending much time making sure you clean up your memory management.

Mark B
  • 95,107
  • 10
  • 109
  • 188