vector 析构问题

1298阅读 0评论2012-11-03 xhb8413
分类:C/C++

 
 
 
 
 
日志
 
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"<上一篇:C++中的动态绑定
下一篇:c中的union的用法和作用