转载:用vector保存对象时保存指针的优点, 以及reserve的使用
2024-10-21 11:34:26
#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 ;
}
执行结果1
A()
other
other
~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 ;
}
结果2
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
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
#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();
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 ;
}
结果
A()
other
other
----------
manual delete----------
~A()
~A()
~A()
----------
最新文章
- 什么是SARG ?
- 利用sp_addlinkedserver实现远程数据库链接
- scikit-learn实现ebay数据分析 的随笔
- Python KeyError
- 【axc】简单的线性动画绘制
- MFC中混合使用Duilib制作界面
- [转Go-简洁的并发 ]
- 获取数组排序后的index算法实现
- CF A and B and Chess
- linux网站配置文件.htaccess伪静态转换到IIS web.config中
- BZOJ 2101: [Usaco2010 Dec]Treasure Chest 藏宝箱( dp )
- 我们究竟什么时候可以使用Ehcache缓存(转)
- ue4玄学画面设置实现
- 看我如何粘贴别人代码--socketserver
- PHP7--PHP的一次重大变革
- PYTHON-进程 子进程
- ZoomCharts
- 计算机基础:计算机网络-chapter3
- vue.js 入门学习
- Python 爬58同城 城市租房信息