归档 2010年3月15日

最后更新于 .

现在代码中越来越多的使用单体类,而我们通常的编写代码的方式是:

在A.h文件中:

class CTest
{
    public:
        static CTest* _ins;
        static CTest* Ins()
};

在A.cpp中:

CTest* CTest::_ins = NULL;
CTest* CTest::Ins()
{
    if ( !_ins )
    {   
        try 
        {   
            _ins = new CTest();
        }   
        catch(...)
        {   
            return NULL;
        }   
    }   
    return _ins;
}

而实际上,上面的代码通过valgrind检查内存泄漏的时候,会告诉你内存still reachable,虽然实际上当进程退出的时候,这些内存是实际释放掉了,但是还是多少会对内存泄漏的定位产生影响,而且也不符合谁申请谁释放的原则。

我们可以简单的使用stl的智能指针解决这个问题,即代码更改如下:

在A.h文件中:

class CTest
{
    public:
        static auto_ptr<CTest> m_auto_ptr;
        static CTest* _ins;
        static ...

昨天

2010年3月11日

明天

2010年3月16日

归档