容器判空
- 问题:写代码通过CI的cppcheck,检测出性能问题。定位到容器的判断
std::list<T> myList;
// some code
// 判空
if (0 != list.size()) {
// dosomething
}
- 原因是,对于std::list,size()的复杂度是O(n),empty的复杂度是O(1)
- 修改后代码
std::list<T> myList;
// some code
// 判空
if (!list.empty()) {
// dosomething
}
指针保护
- 问题:写代码时,没有对指针判空,就直接调用指针的函数。
function()
{
// some code
m_pointer->func();
// some code
}
- 修改后代码如下
function()
{
// some code
if ( null != m_pointer) {
m_pointer->func()
}
else {
// some code for pointer is null
}
// some code
}
总结
- 克服小问题,养成好的编码风格。