代码1
[cpp] view plaincopy
- #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;
- }
执行结果1
[cpp] view plaincopy
- A()
- other
- other
- ~A()
- ~A()
- ~A()
代码2
[cpp] view plaincopy
- #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;
- }
结果2
[cpp] view plaincopy
- A()
- other
- other
- ----------
- other
- other
- ~A()
- other
- other
- other
- ~A()
- ~A()
- other
- other
- other
- other
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
把代码2注释掉的vec.reserve(3)打开, 结果3
[cpp] view plaincopy
- A()
- other
- other
- ----------
- other
- other
- other
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
说明在使用vector时, 插入的是要插入的对象的拷贝, 如果vector中的类对象比较大时, 会影响性能,
还有使用拷贝构造时的一些深浅拷贝的问题, 另外通过结果2与结果3的比较我们可以知道当vector开始申请的空间不够使用时,
它会再次申请空间并可能放弃原来申请的空间, 这样调用的拷贝构造次数就更多了,
所以我们在使用vector前应该通过它的成员函数reserve事先申请一个我们估计的值, 你可以放心, 当reserve的空间不够大时,
vector仍然会自动申请空间
下面是使用vector中存放类指针的做法, 一定要注意插入vector中对象指针指向内容的生存周期问题, 另外如果是new出来的,
如果其他地方没有delete应该在适当的时候通过遍历vector查找出来进行delete
[cpp] view plaincopy
- #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);
- std::vector<A*>::iterator iter = vec.begin();
- for (; iter!=vec.end(); ++iter)
- {
- delete *iter; //*iter = a , b, c
- }
- vec.clear();
- return 0;
- }
结果
[cpp] view plaincopy
- A()
- other
- other
- ----------
- ~A()
- ~A()
- ~A()
CPP-STL:用vector保存对象时保存指针的优点, 以及reserve的使用(转),布布扣,bubuko.com
时间: 2024-10-08 11:13:09