#include <vector>#include <stdio.h>class A{public: A() { printf("A()/n"); } ~A() { printf("~A()/n"); } A(const A& other) { printf("other/n"); }};int main(){ A a; A b(a); A c = a; return 0;}
Execution result 1
A()otherother~A()~A()~A()
Code 2
#include <vector>#include <stdio.h>class A{public: A() { printf("A()/n"); } ~A() { printf("~A()/n"); } A(const A& other) { printf("other/n"); }};int main(){ A a; A b(a); A c = a; printf("----------/n"); std::vector<A> vec; //vec.reserve(3); vec.push_back(a); vec.push_back(b); vec.push_back(c); return 0;}
Result 2:
A()otherother----------otherother~A()otherotherother~A()~A()otherotherotherother~A()~A()~A()~A()~A()~A()~A()~A()~A()
Open Vec. Reserve (3) commented out by code 2. Result 3:
A()otherother----------otherotherother~A()~A()~A()~A()~A()~A()
It indicates that when a vector is used, the inserted object is a copy of the object to be inserted. If the class object in the vector is large, the performance will be affected, as well as some copying problems during the copy construction, in addition, through the comparison between result 2 and result 3, we can know that when the space requested by vector is insufficient, it will apply for space again and may discard the original space, in this way, the number of copy constructor calls is more. Therefore, before using the vector, we should apply for an estimated value through its member function reserve. You can rest assured that, when the reserve space is not large enough, the vector will automatically apply for space.
The following describes how to store class pointers in a vector. Be sure to insert the object pointer in the vector to the content's life cycle. In addition, if the object pointer is new, if there is no delete in other places, you should traverse the vector to find it and perform the delete operation as appropriate.
#include <vector>#include <stdio.h>class A{public: A() { printf("A()/n"); } ~A() { printf("~A()/n"); } A(const A& other) { printf("other/n"); }};int main(){ A *a = new A; A *b = new A(*a); A *c = new A(*a); printf("----------/n"); std::vector<A*> vec; vec.reserve(3); vec.push_back(a); vec.push_back(b); vec.push_back(c); printf("manual delete----------/n"); std::vector<A*>::iterator iter = vec.begin(); for (; iter!=vec.end(); ++iter) { delete *iter; //*iter = a , b, c }
printf("----------/n");
vec.clear();
return 0;
}
Result
A()otherother----------manual delete----------~A()~A()~A()----------