C++ 代码优化

时间:2023-03-09 07:24:08
C++ 代码优化

1、类中所有的属性全部设置为private

然后在需要在外部调用的属性,每个都自己写Get方法返回,或者用Set方法设置

2、类成员变量采用m_前缀,代表类成员

3、采用单例模式

//设置类名为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这个只有一个的实例。

4、用new(std::nothrow)代替new,new的时候如果内存中的堆空间被占满,就会引发异常,而new(std::nothrow)只会返回null。

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

5、使用size _t代替int ,size _t 为了增强程序的可移植性