单例变量的构造除了这样的写法:

    static Base* GetInstance()
    {
        if( nullptr == instance )
        {
            instance = new Base();
        }
        return instance;
    }

还可以利用static变量只执行一次初始化的特性,下面代码的结果都是一样的:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;

class Base
{
public:
    static Base* GetInstance()
    {
        static Base *instance = new Base();
        return instance;
    }
    static int GetRandow()
    {
        static int number = rand() % 100;
        return number;
    }
};

int main()
{
    srand((unsigned)time(NULL));
    cout << "\n";
    printf( "%p\n", Base::GetInstance() );
    printf( "%p\n", Base::GetInstance() );

    cout << Base::GetRandow() << endl;
    cout << Base::GetRandow() << endl;
    cout << Base::GetRandow() << endl;
}

单例内存释放问题:
利用嵌套类可访问访问私有成员的权限和栈变量自动释放内存的特性可以创建内存回收机制。
如下:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;

class TestBase
{
public:
    static TestBase *GetInstance()
    {
        if( nullptr == m_Instance )
        {
            m_Instance = new TestBase();
        }
        return m_Instance;
    }
    ~TestBase()
    {
        cout << "~TestBase()" << endl;
    }

private:
    TestBase(){ cout << "TestBase()" << endl; }

    class MemoryManager
    {
    public:
        ~MemoryManager();
    };
    static MemoryManager m_MemManager;

    static TestBase* m_Instance;
};

TestBase* TestBase::m_Instance = nullptr;
TestBase::MemoryManager TestBase:: m_MemManager;

TestBase::MemoryManager::~MemoryManager()
{
    cout << "~MemoryManager()" << endl;
    if( TestBase::m_Instance )
    {
        delete TestBase::m_Instance;
        TestBase::m_Instance = nullptr;
    }
}

int main()
{
    TestBase::GetInstance();
    return 0;
}

output:

TestBase()
~MemoryManager()
~TestBase()

分类: C plus plus

发表评论

电子邮件地址不会被公开。 必填项已用*标注