C ++ pays attention to small details (2) do not manipulate the vector on the internal data of the Vector

Source: Internet
Author: User

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 );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.