Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector::clear() in constructor and destructor

Tags:

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:

  1. constructor - the class member of type std::vector is empty by default, so no need to call clear().
  2. destructor - the class member of type std::vector will be destroyed as part of standard destruction of object contnaining it. As part of vector destruction all value objects containied in it will be destroyed (if it heap allocated pointers to memory, they should be deleted "manually"), so again no need to call clear().

Do I miss something?

like image 997
dimba Avatar asked Oct 19 '09 20:10

dimba


People also ask

Does STD Vector clear call destructor?

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.

Does Clear () delete a vector?

clear() function is used to remove all the elements of the vector container, thus making it size 0.

Does clear call destructors?

Yes, if there is a destructor defined for the object you're deleting.

How do you destruct a vector in C++?

The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.


2 Answers

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.

like image 96
John Kugelman Avatar answered Sep 20 '22 18:09

John Kugelman


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.

like image 20
Jerry Coffin Avatar answered Sep 20 '22 18:09

Jerry Coffin