C++单件模式(只保留唯一个类对象)

C++单件模式(只保留唯一个类对象)

[user:test] cat main.cpp
/// @file main.cpp
/// @brief
/// EastonWoo
/// 0.01
/// @date 2013-03-10

#include
#include
#include

class Ctest
{
public:
    static Ctest* Instance();

protected:                     //用protected,而不用public的作用:不能直接申请对象,只能通过Instance()申请
    Ctest(){};
    virtual ~Ctest(){};

private:
    friend class std::auto_ptr;                 //
    static std::auto_ptr m_pInstance;     //智能指针,程序退出时会自动释放new Ctest的内存。
    static std::mutex m_InstanceMux;                  //用锁同一时间只能申请一次。安全。

public:
    int m_val;

};

std::auto_ptr Ctest::m_pInstance;
std::mutex Ctest::m_InstanceMux;

Ctest* Ctest::Instance()
{
    m_InstanceMux.lock();
    if(NULL == m_pInstance.get())
    {
        m_pInstance.reset(new Ctest);
    }
    m_InstanceMux.unlock();
    return m_pInstance.get();
}

int main(int argc, const char *argv[])
{
    Ctest* pTest1 = Ctest::Instance();
    pTest1->m_val = 1;

    Ctest* pTest2 = Ctest::Instance();
    pTest2->m_val = 2;

    printf("pTest1->m_val = %d\n",pTest1->m_val);
    printf("pTest2->m_val = %d\n",pTest2->m_val);
    return 0;
}

你可能感兴趣的:(C++编程)