当前位置:网站首页>The advantages of saving pointers when saving objects with vector and the use of reserve

The advantages of saving pointers when saving objects with vector and the use of reserve

2022-06-12 12:08:00 Just want to call Yoko

  Code 1

  Execution results 1

  Code 2

  result 2

  Code 2 Commented out vec.reserve(3) open , result 3

 

  The instructions are in use vector when , What is inserted is a copy of the object to be inserted , If vector When the class object in is large , Will affect performance , There are also some deep and shallow copy problems when using copy construction , In addition, through the results 2 And results 3 We can know when vector When there is not enough space to apply for , It will apply for space again and may give up the original space , In this way, the number of copy constructions called is more , So we're using vector It should be passed through its member function reserve Apply in advance for a value we estimate , You can rest assured , When reserve When the space is not enough , vector Will still automatically apply for space

  Here's how to use vector The method of storing class pointers in , Be sure to insert vector The life cycle of the object pointer pointing to the content in , In addition, if it is new Coming out , If not elsewhere delete It should be traversed in due course vector Find out delete

  result

 

原网站

版权声明
本文为[Just want to call Yoko]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121206219208.html