C++ 代码优化

一、类中全部的属性所有设置为privatespa

    而后在须要在外部调用的属性,每一个都本身写Get方法返回,或者用Set方法设置code

 

二、类成员变量采用m_前缀,表明类成员对象

 

三、采用单例模式blog

//设置类名为CConfig
Class CConfig
{
public://获取单例的静态方法
    static CConfig* GetInstance();  
    //对象实例
    static CConfig* m_pConfig;      
};

CConfig* CConfig::GetInstance()
{
    if (m_pConfig == NULL)
    {
        m_pConfig = new CConfig();
    }
    return m_pConfig;
}

这样在程序的任何地方均可以调用CConfig::GetInstance()来获取CConfig这个只有一个的实例。内存

 

 

四、用new(std::nothrow)代替new,new的时候若是内存中的堆空间被占满,就会引起异常,而new(std::nothrow)只会返回null。class

p* ptr = new(std::nothrow) p;
if (ptr)
{ 
    //do something 
}

 五、使用size _t代替int ,size _t 为了加强程序的可移植性变量

相关文章
相关标签/搜索