Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4208613
  • 博文数量: 176
  • 博客积分: 10059
  • 博客等级: 上将
  • 技术积分: 4681
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-24 12:27
文章分类

全部博文(176)

文章存档

2012年(1)

2011年(4)

2010年(14)

2009年(71)

2008年(103)

分类: C/C++

2008-12-07 22:13:30

By zieckey (http://blog.chinaunix.net/u/16292/)

Trend科技的一道面试题:

请看下面的程序,说说会出现什么问题?

#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日编辑了该文章文章。
-->
阅读(2413) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2008-12-11 21:48:41

hhh

xiaoniuniuxiao2008-12-11 13:26:54

xiaoniuniuxiao