c++实现单例


单例宏:

//单件定义宏
//-------------------------------------
//  在头文件中申明
//    DECLARE_SINGLEOBJ( CSampleClass ) ;
//    在CPP文件中定义静态变量
//    IMPLEMENT_SINGLEOBJ( CSampleClass ) ;
//    注意单件的getInstance为非线程安全,
//  最好是在主线程初始化的时候调用一次
//-------------------------------------
#define DECLARE_SINGLEOBJ(type)        
public:    
    static type* m_instance ;
    static type* getInstance(){
        if( NULL == m_instance ){
            m_instance = new type() ;
        }
        return m_instance ;
    };
    static void release(){
        if( m_instance){
            delete m_instance ;
            m_instance = NULL ;
        }
    };

#define IMPLEMENT_SINGLEOBJ(type) 
    type* type::m_instance = NULL ;

一个实例:

class CNetServer
{
protected:
    CNetServer() ;
    ~CNetServer() ;

    DECLARE_SINGLEOBJ( CNetServer )

public:
    //启动net server
    bool                        StartServer( char *addr , unsigned short port ) ;
    //ping 消息的处理
    void handlePing( ) ; }

应用:

void *CNetServer::pingThreadProc( void *pObj )
{
.................        
    while( true )
    {
        CNetServer::getInstance()->handlePing( ) ;
..................
    }

    return 0 ;
}
原文地址:https://www.cnblogs.com/mylinux/p/6063494.html