文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C++之内存泄露

C++之内存泄露

时间:2010-04-22  来源:llovzy

今天看百度知道上有人问以下代码会不会产生内存泄露:  

class tree
{
    protected:
        int *p;
    public:
        tree();
        ~tree();
};
tree::tree()
{
    p = new int;
}
tree::~tree()
{
    delete p;
}

下面有个人回答的不错,抄录下来,以作备忘

   这段代码有内存泄露的危险,因为C++标准明确指出,当子类对象经由基类指针删除时,倘若基类带有一个non-virtual(非虚)析构函数,此时其结果为undefined(未定义).这在C++中最后变为了一个通用的程序设计方法:既对一个有可能做为基类的类,其析构函数最好声明为virtual的,这可以保证在使用多态的情况下,通过基类指针正确删除子类对象. 分析如下:

考虑从tree类继承,下面是子类代码:

class child:public tree
{
private:
   char *pc;
public:
   child()
   {
      pc=new char[100]; //这里假设此操作不为抛出任何异常

   }
   ~child()
   {
      delete[] pc;
   }
};

tree *pt=new child(); //通过基类指针引用子类对象

delete pt; //此时只是删除刚刚构建的子类对象中的基类成分

                        //而子类的析构函数可能根本不会调用,从而使子类

                         // 的资源发生泄露


   但若将tree类的析构函数加上virtual,则C++会保证在以上的情况下准确调用child的析构函数来释放资源.注意,我的child类析构函数并没有声明为virtual的,因为这里假设其作为tree的子类,而虚拟是有继承性的,当tree析构函数为virtual时,child析构函数自动变为virtual......


动手试试吧

#include <iostream>
using namespace std;

class base{
    private:
        int *pb;
    public:
        base(){
            pb = new int(1);
            cout<<"Base Constructor!"<<endl;
        }
        ~base(){
            delete pb;
            cout<<"Base Destructor!"<<endl;
        }
};

class child:public base{
    private:
        int *pc;
    public:
        child(){
            pc = new int(2);
            cout<<"Child Constructor!"<<endl;
        }
        ~child(){
            delete pc;    
            cout<<"Child Destructor!"<<endl;
        }
};

int main()
{
    base *p = new child();
    delete p;
    system("pause");
    return 0;
}

 

输出:

  Base Constructor!
  Child Constructor!
  Base Destructor!



class base{
    private:
        int *pb;
    public:
        base(){
            pb = new int(1);
            cout<<"Base Constructor!"<<endl;
        }
        virtual ~base(){
            delete pb;
            cout<<"Base Destructor!"<<endl;
        }
};

class child:public base{
    private:
        int *pc;
    public:
        child(){
            pc = new int(2);
            cout<<"Child Constructor!"<<endl;
        }
        virtual ~child(){
            delete pc;    
            cout<<"Child Destructor!"<<endl;
        }
};

输出:

  Base Constructor!
  Child Constructor!
  Child Destructor!
  Base Destructor!

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载