Osetroff
Osetroff

Reputation: 5

How to free resources of QString when use it inside std::vector

I have a structure "rs" for every record of my dataset.

All records are in a vector "r".

My record count is in “rc”.

.... 
struct rs{
  uint ip_i;//index
  QString ip_addr;//ip address
};
std::vector <rs> r;//rows ordered by key
int rc;//row count
....

I would like to control this memory usage. That's why I don't want to use r.insert and r.erase.

When I need to insert a record, I will:

  1. Increase size of r by r.resize(..);r.shrink_to_fit() (if needed).
  2. Shift elements of r to the right (if needed) by std::rotate.
  3. Put new values: r[i].ip_i=...;r[i].ip_addr=...

When I need to delete a record, I will:

  1. Shift elements of r to the left (if needed) by std::rotate. For example, std::rotate(r.begin()+i,r.begin()+i+1,r.begin()+rc);.
  2. Free resources of r[rc].ip_addr. How to free resouces of QString r[rc].ip_addr? I've tried to do r[i].ip_addr.~QString() and catched an runtime error.
  3. Make r.resize() (if needed).

I don't want to loose memory because of Qstring copies stayed after rows deleting.

How can I control them?

Thanks.

Upvotes: 0

Views: 733

Answers (1)

Sergei Tachenov
Sergei Tachenov

Reputation: 24879

QString handles all memory control for you. Just treat it as a regular object and you'll be fine. std::vector is OO-aware, so it will call destructors when freeing elements.

The only thing you should not do is use low-level memory manipulation routines like memcpy or memset. std::vector operations are safe.

If you really want to free a string for a record that is within [0..size-1] range (that is, you do not actually decrease size with resize() after moving elements), then calling r[i].ip_addr.clear() would suffice. Or better yet, introduce the clear() method in your structure that will call ip_addr.clear() (in case you add more fields that need to be cleared). But you can only call it on a valid record, of course, not one beyond your actual vector size (no matter what the underlying capacity is, it's just an implementation detail).

On a side note, it probably makes sense to use QList instead since you're using Qt anyway, unless you have specific reasons to use std::vector. As far as memory control goes, QList offers reserve method which allows you reserve exactly as many elements as you need. Inserting then would look like

list.reserve(list.size() + 1);
list.insert(i, r);

Upvotes: 2

Related Questions