Solved QString array: easy way to clean
-
Hello!
What is the easiest way to clear QString[] array? -
@sitesv Do you mean to empty each QString in the array?
If so https://en.cppreference.com/w/cpp/algorithm/fill comes to my mind. -
@jsulm
When I have worked with AnsiString / UnicodeString, I could use a "memset" function for cleaning array.
But for QString objects, this is not a solution.AnsiString myarray[1000]; ... memset(myarray,0,sizeof(myarray));
Is it possible to clean a QString array without 'for' statement?
-
@sitesv said in QString array: easy way to clean:
AnsiString myarray[1000];
...
memset(myarray,0,sizeof(myarray));this is bad, real bad. The destructor for the strings doesn't get called.
I don't think you can do better than
for(auto& i : myarray) i->clear();
-
@VRonin Thanks! This is it!
@VRonin said in QString array: easy way to clean:
this is bad, real bad. The destructor for the strings doesn't get called.
Why it is bad? It's working!
-
@sitesv said in QString array: easy way to clean:
Why it is bad?
Because of "The destructor for the strings doesn't get called". In worst case not all resources are freed because destructor is not called (depends on what AnsiString is doing internally).
-
From the docs:
An AnsiString variable is a structure containing string information. When the variable is empty (when it contains a zero-length string), the pointer is nil and the string uses no additional storage. When the variable is nonempty, it points to a dynamically allocated block of memory that contains the string value.
You are just overwriting your array memory with all 0 so the memory allocated by
AnsiString
is leaked -
I agree with @VRonin and @jsulm -- using
memset()
causes a memory leak here because it doesn't release the heap-allocated memory.@sitesv said in QString array: easy way to clean:
QString[] array
Also, you should create a
QStringList
instead of aQString[]
array. -
Hi
Just as a note for anyone landing here from google.Using memset() on any kind of Object instances is as good an idea as using torches as
means of lighting at the gasoline depot....