Chinaunix首页 | 论坛 | 博客
  • 博客访问: 851031
  • 博文数量: 254
  • 博客积分: 5350
  • 博客等级: 大校
  • 技术积分: 2045
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-27 13:27
文章分类

全部博文(254)

文章存档

2015年(1)

2014年(9)

2013年(17)

2012年(30)

2011年(150)

2010年(17)

2009年(28)

2008年(2)

分类: C/C++

2012-11-03 18:08:21

 
 
 
 
 
日志
 
vector 析构问题  
 
请看下面的程序,说说会出现什么问题?

#include
#include
#include
using   namespace   std;

class   CDemo   {
public:
    CDemo():str(NULL){};
    ~CDemo()
    {
        if(str)   delete[]   str;
    };
    char*   str;
};

int   main(int   argc,   char**   argv)   {
    CDemo   d1;
    d1.str=new   char[32];
    strcpy(d1.str, "trend   micro");

    vector   *a1=new   vector();
  
    a1->push_back(d1);
    delete   a1;
  
    return EXIT_SUCCESS;
}

这个程序在退出时,会出问题,什么问题?重复delete同一片内存,程序崩溃。
我们把析构函数改为如下,可以更清楚的看到这一点:
    ~CDemo()
    {
        if(str)
        {
            static int i=0;
            cout<<"&CDemo"<管理员在2009年8月13日编辑了该文章文章。
-->
阅读(1173) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~