1

I have a QVector

QVector<const ClassA*> list; 

and I want to know how it is what the best way to clean an QVector in this case.

ClassA is not a QObject.

Waqar
  • 7,722
  • 3
  • 31
  • 42
adir
  • 15
  • 4
  • 2
    Are you creating those pointers with `new`? If so, I suggest you look into either `std::unique_ptr`, `std::shared_ptr`, or their Qt counterparts. – NathanOliver Jul 07 '20 at 12:25
  • 2
    Depends on what you mean by clean – Ayxan Haqverdili Jul 07 '20 at 12:25
  • 1
    The best way is to use Qt algorithm `qDeleteAll()` defined in . It only applies `delete` on all of the vector's elements. You need to call `QVector::clear()` if that's necessary. If the vector-object is going to be destroyed, only `qDeleteAll()` is sufficient – Pie_Jesu Jul 07 '20 at 14:58

5 Answers5

2

Have a look at the documentation of QVector.clear() - I think it answers your question quite well.

To preserve it, I copied it here:

void QVector::clear()

Removes all the elements from the vector.

Note: Until Qt 5.6, this also released the memory used by the vector. From Qt 5.7, the capacity is preserved. To shed all capacity, swap with a default-constructed vector:

QVector<T> v ...;
QVector<T>().swap(v);
Q_ASSERT(v.capacity() == 0);

or call squeeze().

Waqar
  • 7,722
  • 3
  • 31
  • 42
KYL3R
  • 2,906
  • 9
  • 23
  • in this case clear() release only the pointer list from the vector but it not free the memory since the pointer is manually reserved. I try to do something like that for (int index = 0; index < mList.count(); ++index ) { const ClassA* value = const_cast(mList[index ]); delete value ; } – adir Jul 07 '20 at 12:53
2

Here it is in two lines of code:

while (list.count())
     delete list.takeLast();
smacker
  • 153
  • 6
1

I would write :

qDeleteAll(list);
list.clear();

I also advise you to read this post (as you may get something interesting from it) : Does C++11 allow vector<const T>?


EDIT (a few secondes after post) : My apologies to Pie_Jesu who posted a (very) similar comment on the question, which I did not read when I was writting this answer.

Erel
  • 360
  • 3
  • 12
0

in this case clear() release only the pointer list from the vector but it not free the memory.

I try to do something like that

for (int index = 0; index < mList.count(); ++index )
{
    const ClassA* value = const_cast<ClassA*>(mList[index ]);
    delete value ;
}
adir
  • 15
  • 4
0

I would simply suggest loop with a for each over it and delete every pointer. after that clear the vector

for(auto item : list){
    delete item;
}
list.clear();

Or simply use QScopedPointer elements of classA in your list and simply call clear().

Waqar
  • 7,722
  • 3
  • 31
  • 42
tscheppe
  • 432
  • 4
  • 15
  • that can work if the QVoctor contain a pointer of ClassA **QVector** but in my case the QVector contain a const of **ClassA**. – adir Jul 07 '20 at 14:05