首页 > 代码库 > 转载:用vector保存对象时保存指针的优点, 以及reserve的使用
转载:用vector保存对象时保存指针的优点, 以及reserve的使用
#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
A()otherother~A()~A()~A()
代码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;}
结果2
A()otherother----------otherother~A()otherotherother~A()~A()otherotherotherother~A()~A()~A()~A()~A()~A()~A()~A()~A()
把代码2注释掉的vec.reserve(3)打开, 结果3
A()otherother----------otherotherother~A()~A()~A()~A()~A()~A()
说明在使用vector时, 插入的是要插入的对象的拷贝, 如果vector中的类对象比较大时, 会影响性能, 还有使用拷贝构造时的一些深浅拷贝的问题, 另外通过结果2与结果3的比较我们可以知道当vector开始申请的空间不够使用时, 它会再次申请空间并可能放弃原来申请的空间, 这样调用的拷贝构造次数就更多了, 所以我们在使用vector前应该通过它的成员函数reserve事先申请一个我们估计的值, 你可以放心, 当reserve的空间不够大时, vector仍然会自动申请空间
下面是使用vector中存放类指针的做法, 一定要注意插入vector中对象指针指向内容的生存周期问题, 另外如果是new出来的, 如果其他地方没有delete应该在适当的时候通过遍历vector查找出来进行delete
#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;
}
结果
A()otherother----------manual delete----------~A()~A()~A()----------
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。