For example, I have a piece of code as follows:
Class cls_vector_item <br/>{< br/> PRIVATE: <br/> vector <int> data; <br/> Public: <br/> cls_vector_item (INT a_data_num ): data (a_data_num) <br/>{< br/> do_something (); <br/>}</P> <p> void do_it (vector <cls_vector_item> & VCT) <br/> {<br/> for (int cnt = 0; CNT <data. size (); CNT ++) <br/>{< br/> cls_vector_item CVI (10); <br/> VCT. push_back (CVI); <br/>}< br/> int main (INT argc, char ** argv) <br/>{< br/> vector <cls_vector_item> VCT (100); <br/> do_something ()... </P> <p> for (int cnt = 0; CNT <VCT. size (); CNT ++) <br/>{< br/> VCT [CNT]. do_it (& VCT); <br/>}< br/>}
There is no problem with this code.
When VCT. push_back (CVI);, when the internal space of VCT is insufficient, a new space will be applied and the object will be removed!
However, note that this object should have been removed, but the internal object of the object we are currently in will be removed, but it will become garbage, that is, when the VCT applies for space, the old space is destructed, but our objects are still spam objects logically, so it is a tragedy.
Therefore, you must be careful when using VCT in the future and be careful about the structure.
There are two solutions:
(1) Given a certain space of the vector, so that it has enough space.
(2) This design pattern is problematic. We can adjust the structure. For example, write a function do_it elsewhere (INT POs, vector <...> VCT );