#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()
----------

最新文章

  1. 什么是SARG ?
  2. 利用sp_addlinkedserver实现远程数据库链接
  3. scikit-learn实现ebay数据分析 的随笔
  4. Python KeyError
  5. 【axc】简单的线性动画绘制
  6. MFC中混合使用Duilib制作界面
  7. [转Go-简洁的并发 ]
  8. 获取数组排序后的index算法实现
  9. CF A and B and Chess
  10. linux网站配置文件.htaccess伪静态转换到IIS web.config中
  11. BZOJ 2101: [Usaco2010 Dec]Treasure Chest 藏宝箱( dp )
  12. 我们究竟什么时候可以使用Ehcache缓存(转)
  13. ue4玄学画面设置实现
  14. 看我如何粘贴别人代码--socketserver
  15. PHP7--PHP的一次重大变革
  16. PYTHON-进程 子进程
  17. ZoomCharts
  18. 计算机基础:计算机网络-chapter3
  19. vue.js 入门学习
  20. Python 爬58同城 城市租房信息

热门文章

  1. H+后台主题UI框架---整理(三)
  2. os模块详解2
  3. ThreadPoolExecutor 线程池
  4. python+selenium(环境的安装)
  5. UGUI世界坐标转换为UI本地坐标
  6. 超不清视频播放器-用Python将视频转成字符
  7. final关键字所修饰的类有什么特点
  8. [SQL]连续三天有销售额
  9. Microsoft Windows Server 部署
  10. Linux 特殊指令总结(持续更新)