I encounter many times with code where std::vector::clear() of class member of type std::vector is called in constructor and destructor.
I don't see why it's required:
Do I miss something?
char * has no destructor, but vector::clear does call the destructor when the type has it. Yes manual deallocation is necessary unless you store smart_ptr(unique_ptr) in the vector.
clear() function is used to remove all the elements of the vector container, thus making it size 0.
Yes, if there is a destructor defined for the object you're deleting.
The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.
No, you're not missing anything. I suspect this is (harmless) voodoo programming, sort of like setting a pointer to null after freeing it, or randomly calling repaint/revalidate in GUI code. The programmer remembers that it helped with some sort of bug in the past and now adds it unnecessarily "just in case". Who knows, maybe it'll help. Voodoo.
From the sound of things, the people who wrote that code were the ones who missed something. The only time it would make sense to call clear() in a ctor or dtor would be in the middle of some other code. For example, a ctor might read in some data, process it, then read in more data. In such a case, it's probably faster to use a single container for the data as you read it in, and clear it each time, than to create a new container every iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With